Implement Interface dynamically
Is there a way to take an interface and implement it generically? e.g., All functions are implemented either as throw and/or return defaults and properties are implemented as getter/setters. This is for mocking up so I a simple way to create a class based off only the interface. Essentially something similar to whitehole and blackhole except properties are useable. In fact, I suppose it would be nice to have something analogous to them except properties are implemented. Then one could do Blackhole!(Bluehole!C) where Bluehole implements properties as getters and setters.
Re: recursive definition error
On Monday, 7 July 2014 at 09:56:17 UTC, Marc Schütz wrote: On Monday, 7 July 2014 at 02:57:09 UTC, Frustrated wrote: So, I took all the code surrounding the error message(which was a lot of code) and stuck it into one .d file. No errors! Works as expected. So, WTF?!?! I guess now I have to attempt to split the code across modules to see WTF is going on? Maybe this is a modules issue. I know some of the code I'm using deals with module resolution and there was some talk in the main forum about changing something to do with modules. Could this be the issue? D really needs a better fing way to debug templates or improve the error messages. I'm dealing with about 20k lines of code spread across about 100 modules and the error messages are completely useless as when I put all the code surrounding what it says is causing the error, I do not get the error. Realize, this code works fine in 2.064 so it's not a coding issue as if something magical with my fingers when I copy the code from the modules into a single .d file. Either something was fixed or something was broke... after all the work I spend trying to figure out what was causing the problem, I'm just as clueless. Have you tried dustmite? It can also reduce source code split over several files. Thanks, I'll check it out.
dustmite build
when I build dustmite using dmd or gdc with no options or -O3, it is 18M but in the dmd directory, dustmite is only 650k. I assume I'm statically linking the whole library while in the small one is using some dynamic link library? Or is all that debug information or what?
Re: dustmite build
On Monday, 7 July 2014 at 17:50:35 UTC, Frustrated wrote: when I build dustmite using dmd or gdc with no options or -O3, it is 18M but in the dmd directory, dustmite is only 650k. I assume I'm statically linking the whole library while in the small one is using some dynamic link library? Or is all that debug information or what? Also, how does one use dustmite on a project that invloves many subfolders and uses a library that is specified in the lib path in sc.ini, that also uses many directories? e.g., import a.b.c.d. Say the regression is in the library(worked in one version, new dmd version doesn't work cause it broke something in the library). Is dustmite going to pull in the problematic code from the library or is it too going to just crap out and now show the real problem?
Re: recursive definition error
On Friday, 4 July 2014 at 21:15:02 UTC, Frustrated wrote: On Friday, 4 July 2014 at 20:25:28 UTC, Frustrated wrote: On Friday, 4 July 2014 at 16:31:28 UTC, Stanislav Blinov wrote: On Friday, 4 July 2014 at 16:28:48 UTC, Frustrated wrote: On Friday, 4 July 2014 at 15:42:36 UTC, bearophile wrote: Frustrated: I'm not using 2.066 though... I will revert back to the dmd version I was using when it worked... Hopefully someone can make sure this is not a regression in the mean time... (seems like it is and I don't want to get bit again later on when I upgrade) That template and its instantiation work fine for me on both 2.065 and 2.066b1. Ok, I do not know where this error creeped in at. I do know at one point the code was working fine without any changes I believe. (it's possible though I messed something up) The recursive error seems to be the wrong issue. Trying to diagnose what the problem is now. This must be some weird issue with Array or a change in what imports does. e.g., if I do struct apple(T) { } template Array(T) { alias apple!T Array; } Then the code works(except I no longer can use array as an array but I do not get any recursive issues. The compiler I was using when it worked might have been pre 2.064... Or possibly something else is going on that breaks the code. Best I can tell is that the compiler is getting confused between std.container.Array and my Array. This seems to be a regression as it works fine in 2.064. The error is not directly due to recursion as far as I can tell but in a template that uses the Array template. Why it breaks the array I have no idea. I will try to create a minimal project for it.
Re: recursive definition error
So, I took all the code surrounding the error message(which was a lot of code) and stuck it into one .d file. No errors! Works as expected. So, WTF?!?! I guess now I have to attempt to split the code across modules to see WTF is going on? Maybe this is a modules issue. I know some of the code I'm using deals with module resolution and there was some talk in the main forum about changing something to do with modules. Could this be the issue? D really needs a better fing way to debug templates or improve the error messages. I'm dealing with about 20k lines of code spread across about 100 modules and the error messages are completely useless as when I put all the code surrounding what it says is causing the error, I do not get the error. Realize, this code works fine in 2.064 so it's not a coding issue as if something magical with my fingers when I copy the code from the modules into a single .d file. Either something was fixed or something was broke... after all the work I spend trying to figure out what was causing the problem, I'm just as clueless.
recursive definition error
After upgrading to latest dmd, I get the follow error on the code template Array(T) { alias Array = std.container.Array!T; } Error: Array!(iDataBlock).Array recursive alias declaration I don't see anything recursive about it... and the code worked before. Any ideas?
Re: recursive definition error
On Friday, 4 July 2014 at 15:10:14 UTC, bearophile wrote: Frustrated: After upgrading to latest dmd, I get the follow error on the code template Array(T) { alias Array = std.container.Array!T; } Try to use a different name inside the template, like Vector. Bye, bearophile Huh? The template is simply wrapping std.container.Array so I can later on use change it to a different array without breaking code that uses it. As I said, it worked fine before without this recursion problem. Since there is no recursion going on there, it shouldn't be a problem. This seems like a bug/regression. An indirection does not help.
Re: recursive definition error
On Friday, 4 July 2014 at 15:37:52 UTC, Marc Schütz wrote: On Friday, 4 July 2014 at 15:07:00 UTC, Frustrated wrote: After upgrading to latest dmd, I get the follow error on the code template Array(T) { alias Array = std.container.Array!T; } Error: Array!(iDataBlock).Array recursive alias declaration I don't see anything recursive about it... and the code worked before. Any ideas? Which version of DMD exactly? This works in DMD git. I don't remember what I was using before, I think 2.064. I just upgraded to the latest 2.065.2 today and tried to compile some old code and got all these errors. The code was working fine before. Obviously I could have done something that I forgot but the errors are saying the templates are recursive as if the method doesn't work, yet it worked fine before.
Re: recursive definition error
On Friday, 4 July 2014 at 15:42:36 UTC, bearophile wrote: Frustrated: Since there is no recursion going on there, it shouldn't be a problem. Yes, sorry. In dmd 2.066 this too could work: alias Array(T) = std.container.Array!T; Bye, bearophile That just gives more errors. I'm not using 2.066 though... I will revert back to the dmd version I was using when it worked... Hopefully someone can make sure this is not a regression in the mean time... (seems like it is and I don't want to get bit again later on when I upgrade)
Re: recursive definition error
On Friday, 4 July 2014 at 16:31:28 UTC, Stanislav Blinov wrote: On Friday, 4 July 2014 at 16:28:48 UTC, Frustrated wrote: On Friday, 4 July 2014 at 15:42:36 UTC, bearophile wrote: Frustrated: I'm not using 2.066 though... I will revert back to the dmd version I was using when it worked... Hopefully someone can make sure this is not a regression in the mean time... (seems like it is and I don't want to get bit again later on when I upgrade) That template and its instantiation work fine for me on both 2.065 and 2.066b1. Ok, I do not know where this error creeped in at. I do know at one point the code was working fine without any changes I believe. (it's possible though I messed something up) The recursive error seems to be the wrong issue. Trying to diagnose what the problem is now.
Re: recursive definition error
On Friday, 4 July 2014 at 20:25:28 UTC, Frustrated wrote: On Friday, 4 July 2014 at 16:31:28 UTC, Stanislav Blinov wrote: On Friday, 4 July 2014 at 16:28:48 UTC, Frustrated wrote: On Friday, 4 July 2014 at 15:42:36 UTC, bearophile wrote: Frustrated: I'm not using 2.066 though... I will revert back to the dmd version I was using when it worked... Hopefully someone can make sure this is not a regression in the mean time... (seems like it is and I don't want to get bit again later on when I upgrade) That template and its instantiation work fine for me on both 2.065 and 2.066b1. Ok, I do not know where this error creeped in at. I do know at one point the code was working fine without any changes I believe. (it's possible though I messed something up) The recursive error seems to be the wrong issue. Trying to diagnose what the problem is now. This must be some weird issue with Array or a change in what imports does. e.g., if I do struct apple(T) { } template Array(T) { alias apple!T Array; } Then the code works(except I no longer can use array as an array but I do not get any recursive issues. The compiler I was using when it worked might have been pre 2.064... Or possibly something else is going on that breaks the code. Best I can tell is that the compiler is getting confused between std.container.Array and my Array.
Structs insted of classes for Performance
I know the difference between a struct and a class but I remember seeing somewhere that structs are much faster than classes in D for some strange reason. I'm not worried too much about class allocation performance because I will try and use classes when they will not be created frequently and structs or class reuse when they will be. So, is the only argument really about performance when creating structs vs creating classes or was there some finer detail I missed? Basically that boils down to stack allocation vs heap allocation speed? Which, while allocation on the heap shouldn't be too much slower than stack, the GC makes it worse?
Re: Structs insted of classes for Performance
On Sunday, 20 April 2014 at 16:56:59 UTC, Ali Çehreli wrote: My understanding is not perfect. There may be compiler and CPU optimizations that I am not aware of. On 04/20/2014 08:03 AM, Frustrated wrote: is the only argument really about performance when creating structs vs creating classes Not only creating but also when using. A class variable is a reference to the actual object, implemented by the compiler as a pointer. So, there is that extra indirection overhead to access member variables of a class object. When the class variable and the object are far apart in memory, they may be fall outside of CPU caches. Further, unless they are defined as final or static, class member functions are virtual. Virtual member funtions are dispatched through the virtual function table (vtbl) pointer. So, a call like o.foo() must first hit the class vtbl in memory, read the value of the function pointer off that table and then jump to the function. Related to the above, class objects are larger than struct objects because they have the extra vtbl pointer, as well as another pointer (monitor) that allows every class object to be used as a synchronization item in concurrency. Larger objects are more expensive because less of those can fit in CPU caches. Yes, but this is the standard argument between structs and classes. Obviously the additional benefits of classes cost... else no one would use structs. If structs had inheritance, there would be no real reason for classes. I don't mind the cost of classes because I will try and use them were appropriately. Also, these problems are not language specific but simply because classes are heavier. The article I read was about D's specific issues and that using structs GREATLY sped up certain things... I'm sure it had to do with the GC and all that but can't remember. Basically that boils down to stack allocation vs heap allocation speed? Not to forget, struct objects can be allocated on the stack as well by std.typecons.scoped. Which, while allocation on the heap shouldn't be too much slower than stack, the GC makes it worse? Stack allocation almost does not exist as some location on the stack is reserved for a given object. There is no allocation or deallocation cost at runtime other than certain decisions made by the compiler at compile time. On the other hand, any dynamic allocation and deallocation scheme must do some work to find room for the object at runtime. Ali Again, all those arguments are about the specific difference between a struct and class and apply to all languages that use those types of structures. In D though, I guess because of the GC(but which is why I am asking because I don't know specifically), classes could be much slower due to all the references causing the GC to take longer scan the heap and all that. If allocate or free a lot of classes in a short period of time it also can cause issues IIRC. I just can't remember if there was some other weird reasons why D's classes are, in general, not as performant as they should be. If I remember correctly, I came across a page that compared a few test cases with the GC on and off and there was a huge factor involved showing that the GC had a huge impact on performance.
Re: can I generate an enum from a typelist?
On Tuesday, 8 April 2014 at 08:31:16 UTC, Vlad Levenfeld wrote: Ok, starting to feel a bit sheepish at this point, that constructor was unnecessarily verbose: this (T) (T layer) { import std.string: toLower; mixin (this.~toLower (T.stringof)~= layer;); this.type = cast (const) typeid (T); } ...is what I have settled on. Sorry for all the noise! There doesn't seem to be a way to edit posts here... You can simply reflect on your nested structs and generate the enum from them. No need to duplicate anything. The only thing you have to do is figure out how to determine if a nested struct is part of the enum. If all nested structs of Layer are then it is easy. Else some naming scheme or inheritance needs to be used to distinguish them from others.
Re: Why defining alias and not auto when using a template?
On Friday, 4 April 2014 at 13:23:48 UTC, Bienlein wrote: Hello, I took some code snippet from some sample D code and modified it a bit: template TCopy(T, V) { private int i = 2; void copy(out T to, out V to2, T from) { to = from; to2 = from; writeln(i: , i); } } void main(string[] args) { int x = 2; int y = 2; alias myCopy = TCopy!(int, int); myCopy.copy(x, y, 37); writeln(x: , x, y: , y); } My question is now why I have to declare and alias as in alias myCopy = TCopy!(int, int); If I define auto instead of alias, it does not compile. My question is why defining auto does not work. I would consider this more intuitive. Thanks, Bienlein When you type TCopy!(int, int) you are not creating an expression with a return variable. TCopy!(int, int) has no return variable so auto can't work(What would be the return value?). All TCopy is, is a compile time container that contains a variable i and a method copy. It contains no return value, hence auto can't work. Now, TCopy!(int, int).i or TCopy!(int, int).copy are things that are in the template that can be used. About the only thing you could do is use an eponymous template like template TCopy(T, V) { private int i = 2; void copy(out T to, out V to2, T from) { to = from; to2 = from; writeln(i: , i); } T TCopy() { return null; } } then auto x = TCopy!(int, int)(someTvalue); then x would be of type T, the return value of the TCopy function(not the template because it doesn't have a return value).
How to dynamically call class virtual method dynamically
Basically in programming to interfaces I need to decide to call a virtual method of an object if it exists else call a final method in the interface: interface A { static final void foo() { ... } } class B : A { void bar() { ... } // optional } class C : B { void bar() { ... } // optional } void main() { A a = new B; // or new C; // if a.bar exists call it, else call foo // code should work independent of the classes. (there might be more) } The point of the code is simply to allow the class to implement bar optionally but provide default behavior with foo. I need a way to dynamically determine if bar exists and fall back on foo. This should be possible. e.g., suppose class B : A { } then I would like to b.bar() to actually call A.foo() (since bar doesn't exist in b). I guess the exist way would be to create an opDispatch and have it call foo if bar is passed. This works great and does everything I need it to except requires adding the code in the class which I can't have. Also I'm not sure how it would work with virtual methods. I've tried using hasMember but since my object is cast to a type of Object it never works.
Re: How to dynamically call class virtual method dynamically
On Tuesday, 1 April 2014 at 12:20:06 UTC, Steven Schveighoffer wrote: On Tue, 01 Apr 2014 03:31:41 -0400, Frustrated w...@where.com wrote: Basically in programming to interfaces I need to decide to call a virtual method of an object if it exists else call a final method in the interface: interface A { static final void foo() { ... } } class B : A { void bar() { ... } // optional } class C : B { void bar() { ... } // optional } void main() { A a = new B; // or new C; // if a.bar exists call it, else call foo // code should work independent of the classes. (there might be more) } The point of the code is simply to allow the class to implement bar optionally but provide default behavior with foo. I need a way to dynamically determine if bar exists and fall back on foo. This should be possible. e.g., suppose class B : A { } then I would like to b.bar() to actually call A.foo() (since bar doesn't exist in b). I guess the exist way would be to create an opDispatch and have it call foo if bar is passed. This works great and does everything I need it to except requires adding the code in the class which I can't have. Also I'm not sure how it would work with virtual methods. Detecting whether bar exists can only happen at compile time, since an instance of A has no mechanism to detect whether it has bar. D does not have very good runtime introspection, that would have to be built into the TypeInfo struct (the mechanism exists to do it, but it has never been used for that). You could use this templates, but that would only work if the type of the derived class is known at compile time. This problem could easily be solved by virtual methods with default implementation. -Steve It seems logical to me that I should be able to achieve what I what. Suppose I have an object cast to it's interface: A a = new B; when I call a.This() it will call the method in the interface. Either This is a virtual method or a final method. Suppose it is a Final method since if it is virtual there is no problem. Now suppose B implements That as a virtual method that doesn't exist in A. Since a IS a B, That exists in it's vtable. I should be able to call it: a.That(); // Calls B's That(). Of course this doesn't work directly because That() is not part of the interface. Regardless though, it still exists: (cast(B)a).That(); // Works But the only problem is that the cast(B) is required and is a trick to get the compiler to do what I want. But we know that a is of type B. e.g., typeof(cast(Object)a) returns B, right? Basically, it should be very easy for the compiler to internally cast a object to it's actual type(since that is contained in the object information, even if it's cast to something else) and call members on it. Of course, I'm not asking for an internal way. I could be mistaken but isn't `A a = new B` just a facade and a really is of type B? If so, isn't there a way to get the true type of a at runtime? If so, then can't we cast a to its true type at runtime and access its members properly? e.g., suppose truecast(a) returns a as the actual object that a was created as(in this case B, not A). Then truecast(a).That() would work. I'm sort of looking for the truecast function/template. Of course, if D doesn't store information about the actual type an object is inside it(which it doesn't AFAIK) then you can't truecast.
Re: How to dynamically call class virtual method dynamically
On Tuesday, 1 April 2014 at 19:52:47 UTC, Steven Schveighoffer wrote: On Tue, 01 Apr 2014 15:00:17 -0400, Frustrated w...@where.com wrote: On Tuesday, 1 April 2014 at 12:20:06 UTC, Steven Schveighoffer wrote: On Tue, 01 Apr 2014 03:31:41 -0400, Frustrated w...@where.com wrote: Basically in programming to interfaces I need to decide to call a virtual method of an object if it exists else call a final method in the interface: interface A { static final void foo() { ... } } class B : A { void bar() { ... } // optional } class C : B { void bar() { ... } // optional } void main() { A a = new B; // or new C; // if a.bar exists call it, else call foo // code should work independent of the classes. (there might be more) } The point of the code is simply to allow the class to implement bar optionally but provide default behavior with foo. I need a way to dynamically determine if bar exists and fall back on foo. This should be possible. e.g., suppose class B : A { } then I would like to b.bar() to actually call A.foo() (since bar doesn't exist in b). I guess the exist way would be to create an opDispatch and have it call foo if bar is passed. This works great and does everything I need it to except requires adding the code in the class which I can't have. Also I'm not sure how it would work with virtual methods. Detecting whether bar exists can only happen at compile time, since an instance of A has no mechanism to detect whether it has bar. D does not have very good runtime introspection, that would have to be built into the TypeInfo struct (the mechanism exists to do it, but it has never been used for that). You could use this templates, but that would only work if the type of the derived class is known at compile time. This problem could easily be solved by virtual methods with default implementation. -Steve It seems logical to me that I should be able to achieve what I what. Suppose I have an object cast to it's interface: A a = new B; when I call a.This() it will call the method in the interface. Either This is a virtual method or a final method. Suppose it is a Final method since if it is virtual there is no problem. Now suppose B implements That as a virtual method that doesn't exist in A. Since a IS a B, That exists in it's vtable. I should be able to call it: a.That(); // Calls B's That(). There is no definition for B's vtable according to A. It just looks like an array of void pointers. In other words, there's no possible way, without knowing B's type structure, to know which entry in the vtable is 'That'. Of course this doesn't work directly because That() is not part of the interface. Regardless though, it still exists: (cast(B)a).That(); // Works Because you have (at runtime) determined that a actually IS a 'B'. But the only problem is that the cast(B) is required and is a trick to get the compiler to do what I want. It's not a trick, it's a runtime check. It basically is saying if a is actually a B, then call B.That, otherwise segfault But we know that a is of type B. The compiler/runtime does not know that. e.g., typeof(cast(Object)a) returns B, right? You are thinking of typeid. But the runtime information does not contain any way to figure out which location 'That' is at. What you are really looking for is runtime introspection, similar to Java or C#. D has the capability, but it has not been implemented. We only have compile-time introspection. I could be mistaken but isn't `A a = new B` just a facade and a really is of type B? a is of type A, and it points at an instance of B. If so, isn't there a way to get the true type of a at runtime? If so, then can't we cast a to its true type at runtime and access its members properly? You can get at B's typeinfo, but that doesn't contain a way to call arbitrarily named functions. e.g., suppose truecast(a) returns a as the actual object that a was created as(in this case B, not A). Then truecast(a).That() would work. With the correct implementation of RTInfo inside object.di, you could possibly make this work. It would be kind of cool. It would be a TON of work to make this a reality. -Steve Here is a basic outline of a possible approach. I do not believe it is the best way import std.stdio, std.cstream; interface A { public final void opDispatch(string m)() { opDispatchImpl(m); } protected bool opDispatchImpl(string m); // void bar() { writeln(hello); } // possible but name conflict } class B : A { void bar() { writeln(asdfasdf); } override bool opDispatchImpl(string m) { if (m == bar) bar(); return false; } } void main() { A a = new B; B b = new B; a.bar(); // Wow, A doesn't have a bar yet we call it?!?! b.bar(); din.getc(); } Note
Re: Template magic exercise
On Sunday, 30 March 2014 at 12:42:16 UTC, Jack Applegame wrote: Target is to create a template for mapping member array accessor to member function. For example: class Foo { ... int elementsAccessor(size_t index) { ... } ... mixin MagicTemplateMixin!(elements, elementsAccessor); // or better alias elements = SuperMagicTemplate!elementsAccessor; } and now we can call Foo.getter like this: auto foo = new Foo; int el = foo.elements[10]; // int el = foo.getter(10); I wrote poor and ugly solution with proxy structure: http://dpaste.dzfl.pl/93085910f8c7 I hate it. :) I need more powerful spell, but my magic level is too low. While this doesn't work maybe you can put in a request to add the functionality: import std.stdio, std.cstream; import std.variant; import std.conv; class Foo { Variant[] opDispatchIndex(string name, E...)(E elements) { writeln(name); return null; } } void main() { auto f = new Foo; f.elements[3]; // Works if opDispatchIndex existed din.getc(); } alternatively, if you don't mind the extra bloat: import std.stdio, std.cstream; import std.variant; import std.conv; struct opIndexStruct { void opIndex(in size_t i) { writeln(op - , i); } } class Foo { @property opIndexStruct elements() { opIndexStruct o; return o; } } void main() { auto f = new Foo; f.elements[3]; din.getc(); } this works because elements is a property and we don't have to call with parenthesis. e.g., f.elements()[3]. Hence f.elements works. [3] is acted on by the return value of elements(), which is a struct that supports opIndex(one could alternative use alias this to wrap the struct in a type that supports indexing. As is the code isn't very useful but should provide you with the ability to achieve what you want.
Compile time only delegates
Due to a previous issue I am trying to do the following mixin template A() { mixin((function () = int x;)() ); } the problem is that the compiler will not let me use the delegate because it has no this context. Of course the whole point here is that the delegate will never be used at runtime since it is used in the mixin(which is purely compile time). It should work(there is no reason it shouldn't) yet it doesn't. The goal is that I do not want to create a function outside the mixin to use because it will be included in the context of the template mixin. e.g., mixin template A() { string B() { return int x;; } mixin(B()); // still doesn't work but if it did B would be inserted in the context of the template. e.g., if used in a class the class would then have a method named B in it, hence the use of the lambda. }
Re: Compile time only delegates
On Tuesday, 25 March 2014 at 18:10:17 UTC, Meta wrote: On Tuesday, 25 March 2014 at 18:05:47 UTC, Frustrated wrote: Due to a previous issue I am trying to do the following mixin template A() { mixin((function () = int x;)() ); } the problem is that the compiler will not let me use the delegate because it has no this context. Of course the whole point here is that the delegate will never be used at runtime since it is used in the mixin(which is purely compile time). It should work(there is no reason it shouldn't) yet it doesn't. The goal is that I do not want to create a function outside the mixin to use because it will be included in the context of the template mixin. e.g., mixin template A() { string B() { return int x;; } mixin(B()); // still doesn't work but if it did B would be inserted in the context of the template. e.g., if used in a class the class would then have a method named B in it, hence the use of the lambda. } There shouldn't be a context pointer at all as you specified that it's a function, not a delegate. Function literals don't have context pointers as far as I know. Did you try: mixin((function () { return int x; })()); Just to be sure? Thanks, I thought I did try that(that was the first thing I tried I thought). Seems to be working though.
Re: Compile time only delegates
On Tuesday, 25 March 2014 at 20:20:29 UTC, Frustrated wrote: On Tuesday, 25 March 2014 at 18:10:17 UTC, Meta wrote: On Tuesday, 25 March 2014 at 18:05:47 UTC, Frustrated wrote: Due to a previous issue I am trying to do the following mixin template A() { mixin((function () = int x;)() ); } the problem is that the compiler will not let me use the delegate because it has no this context. Of course the whole point here is that the delegate will never be used at runtime since it is used in the mixin(which is purely compile time). It should work(there is no reason it shouldn't) yet it doesn't. The goal is that I do not want to create a function outside the mixin to use because it will be included in the context of the template mixin. e.g., mixin template A() { string B() { return int x;; } mixin(B()); // still doesn't work but if it did B would be inserted in the context of the template. e.g., if used in a class the class would then have a method named B in it, hence the use of the lambda. } There shouldn't be a context pointer at all as you specified that it's a function, not a delegate. Function literals don't have context pointers as far as I know. Did you try: mixin((function () { return int x; })()); Just to be sure? Thanks, I thought I did try that(that was the first thing I tried I thought). Seems to be working though. oops, sorry, same problem. When used inside a class says I need this: Heres the actual code: import std.stdio, std.cstream; // mixin template used to wrap the string mixin mixin template C() { mixin((function () { return void foo(iA a) { writeln(`Generic`); }; })()); } // eponymously named template used as a string mixin to generate the function template B() { string B() { return void foo(iA a) { writeln(`Generic`); }; } } interface iA { void foo(iA a); } class A : iA { void foo(A a) { writeln(Specific); } //mixin(B); mixin C;// doesn't work, use line above (mixin templates won't override even if different parameters) } void main() { iA a = new A; a.foo(a); // Generic/Generic (cast(A)a).foo(cast(A)a); // Specific/Specific a.foo(cast(A)a);// Generic/Specific (cast(A)a).foo(a); // Specific/Generic line doesn't work when using mixin template writeln(-); mixin C; foo(a); din.getc(); } and the error: Error: function main.A.C!().__funcliteral1 need 'this' to access member __funcliteral1 (this only happens using the mixin C in the class, not in main or when using mixin B)
Re: TDPL question: objects may not embed internal pointers, classes too?
On Sunday, 16 March 2014 at 18:41:51 UTC, Adam D. Ruppe wrote: On page 249 of TDPL (Andrei's book), in a section on structs and postblits, it says D objects must be relocatable and other similar statements while banning internal pointers. I knew this applies to structs and the context makes that plainly clear, but the word object is a bit ambiguous: does this apply to classes too? And object is an instantiation of a class. I guess it could be ambiguous but generally I think object = class(misnomer but simple). Structs can exist on the heap and be very similar to objects and I suppose it is possible to allocate classes on the stack so theoretically I guess it is ambiguous but in programming parlance it is not.
Re: Template mixins - why only declarations
On Thursday, 6 March 2014 at 17:27:35 UTC, Steve Teale wrote: Pretty much what the subject says. Why can't template mixins include statements ans so on? Is it just too hard, or is it just too much like C macros? Steve template mixins mix in directly into the code as if you typed them. If they contained statements then you could mixin statements into classes, say, and it would then be illegal. I guess there is no reason per se, but I guess that wasn't the desired behavior for template mixins. I imagine there could be a definite downside to having template mixins containing statements. Also, they can't be self contained. e.g., mixin template C() { i = i + 1; // invalid } ... int i = 0; mixin C(); The template itself can't be semantically checked in place because i is unknown inside the template. (it is not self contained so to speak) In any case, just seems wrong for templates to do that. They are not grouping expressions but grouping definitions and declarations of things so you don't have to do them multiple times. string mixins, OTOH, could do the above. template C() { string C() { return i = i + 1;; } } ... int i = 0; mixin(C); and this will work. This is because the statement is contained within a string and the compiler simply inserts the string directly. The template can still be validated in place(since i = i + 1 is a string and has no other meaning in the template).
Strange Mixin issue
I am trying to remove the unnecessary passing of the type of class to a template but can't seem to get it to work: see The code is the mixin(AbstractToInterface!(WindowsGui, iButton, WindowsButton, iBorder, WindowsBorder)); which I want to not have to specify WindowsGui. I've tried wrapping AbstractToInterface in a mixin template and use that and typeof(this) but then the mixin of the mixin does not get mixed in to the class e.g., mixin template AbstractToInterface2(T...) { mixin(AbstractToInterface!(typeof(this), T)); } Then use mixin AbstractTointerface2!(iButton, WindowsButton, iBorder, WindowsBorder). It's probably something stupid but I can't seem to get it to work(have a very similar case in some other code and it works fine... the only difference is I'm not using nested mixins.
Re: Strange Mixin issue
On Wednesday, 5 March 2014 at 22:35:46 UTC, Ali Çehreli wrote: On 03/05/2014 01:30 PM, Frustrated wrote: I am trying to remove the unnecessary passing of the type of class to a template but can't seem to get it to work: see The code is the mixin(AbstractToInterface!(WindowsGui, iButton, WindowsButton, iBorder, WindowsBorder)); which I want to not have to specify WindowsGui. I've tried wrapping AbstractToInterface in a mixin template and use that and typeof(this) but then the mixin of the mixin does not get mixed in to the class e.g., mixin template AbstractToInterface2(T...) { mixin(AbstractToInterface!(typeof(this), T)); } Then use mixin AbstractTointerface2!(iButton, WindowsButton, iBorder, WindowsBorder). It's probably something stupid but I can't seem to get it to work(have a very similar case in some other code and it works fine... the only difference is I'm not using nested mixins. The following works for me maybe because the templates are not mixin templates. What's a mixin template again? import std.typetuple; template fooImpl(This, T...) { static assert(is (This == S));// -- IT WORKED! static assert(is (T == TypeTuple!(int, double))); } template foo(T...) { alias foo = fooImpl!(typeof(this), T); } struct S { mixin foo!(int, double); } void main() { auto s = S(); } Even better: import std.typetuple; template fooImpl(T...) { static assert(is (T[0] == S));// -- COOL! static assert(is (T[1] == int)); static assert(is (T[2] == double)); } template foo(T...) { alias foo = fooImpl!(TypeTuple!(typeof(this), T)); } struct S { mixin foo!(int, double); } void main() { auto s = S(); } Ali this is not quite the same. You have static asserts. I'm trying to avoid mixing in ctfe code that might interfer with the class. (I have a temp function Do which if I mixin as a normal template will mixin Do into the class make Do a member of that class)
Re: Strange Mixin issue
On Wednesday, 5 March 2014 at 23:04:06 UTC, Ali Çehreli wrote: On 03/05/2014 02:37 PM, Frustrated wrote: import std.typetuple; template fooImpl(T...) { static assert(is (T[0] == S));// -- COOL! static assert(is (T[1] == int)); static assert(is (T[2] == double)); } template foo(T...) { alias foo = fooImpl!(TypeTuple!(typeof(this), T)); } struct S { mixin foo!(int, double); } void main() { auto s = S(); } Ali this is not quite the same. I think you tried to give a link in your original code but it is missing. Still, it is very difficult for me to follow code unless it is really simple. :) You have static asserts. Just to prove that I've managed to inject typeof(this) as the first template parameter. I'm trying to avoid mixing in ctfe code that might interfer with the class. (I have a temp function Do which if I mixin as a normal template will mixin Do into the class make Do a member of that class) The following is what I understand so far. :) The last line of main() proves that S gained a function Do() that takes (int, double) parameters. import std.typetuple; template DoImpl(T...) { auto Do(T[1] p1, T[2] p2) { return p1 + p2; } } template Do(T...) { mixin DoImpl!(TypeTuple!(typeof(this), T)); } struct S { mixin Do!(int, double); } void main() { auto s = S(); assert(s.Do(1, 2.5) == 3.5); } Ali And this is exactly what I don't what! Do, in my case, is a ctfe used only at compile time to make it easy to generate code. It's not needed at runtime and does not belong anywhere.
enum return type
how does an enum return type work? enum foo(string s) { return s; } is it a purely compile time construct? That is, we can guarantee that foo, as a function, won't exist at runtime? e.g., it is a true ctfe instead of a function that can be executed at compile time or runtime?
Re: enum return type
On Wednesday, 5 March 2014 at 23:20:08 UTC, bearophile wrote: Frustrated: how does an enum return type work? enum foo(string s) { return s; } As far as I know that's not valid D (but D is extremely tolerating). Bye, bearophile Well, it works... not sure exactly what it's doing though.
Re: Strange Mixin issue
Maybe the problem isn't what I thought it was. I created a test case that works: import std.stdio, std.cstream; mixin template C() { alias A = typeof(this); mixin(B!(A)); } template B(T) { pragma(msg, T); enum B() { return string foo() { return `~T.stringof~`; }; } } class A { //mixin(B!(A)); mixin C; } void main() { auto a = new A; writeln(a.foo()); //a.B(); din.getc(); } Note the difference in calls. C is much easier because you don't have to pass the parent type. This is all I'm trying to achieve in the other code but when I do the functions(foo in this case) do not get mixed in.
Re: Strange Mixin issue
On Wednesday, 5 March 2014 at 23:33:25 UTC, Frustrated wrote: Maybe the problem isn't what I thought it was. I created a test case that works: import std.stdio, std.cstream; mixin template C() { alias A = typeof(this); mixin(B!(A)); } template B(T) { pragma(msg, T); enum B() { return string foo() { return `~T.stringof~`; }; } } class A { //mixin(B!(A)); mixin C; } void main() { auto a = new A; writeln(a.foo()); //a.B(); din.getc(); } Note the difference in calls. C is much easier because you don't have to pass the parent type. This is all I'm trying to achieve in the other code but when I do the functions(foo in this case) do not get mixed in. The actual error is quite strange in the other code: When I simply wrap the code in an outside template I get the error(s) Eror: gui.border is not an lvalue which is related to the line auto ress = (gui.border = bb); which works when I don't wrap the code. If I stick the output of the string mixin template directly into the class, it works fine. (so it has something to do wtih the template generation rather than what it generates) e.g., this is what I did template AbstractToInterface(B, T...) { enum AbstractToInterface() { } } to mixin template AbstractToInterface(B, T...) { mixin(AbstractToInterface2!(B, T)); } template AbstractToInterface2(B, T...) { enum AbstractToInterface2() { } } and convert mixin(AbstractToInterface!(WindowsGui, iButton, WindowsButton, iBorder, WindowsBorder)); to mixin AbstractToInterface!(WindowsGui, iButton, WindowsButton, iBorder, WindowsBorder); and I get the error down the road about Eror: gui.border is not an lvalue Which I guess is saying border does not have a setter, which is what AbstractToInterface is suppose to be creating and adding... again, it works when I copy the output of the template direct to the class. I'm betting it's a bug unless I'm doing something real stupid.
Re: enum return type
On Wednesday, 5 March 2014 at 23:36:34 UTC, Adam D. Ruppe wrote: On Wednesday, 5 March 2014 at 23:17:45 UTC, Frustrated wrote: is it a purely compile time construct? I think it is the same as auto return functions. Both auto and enum in this context are storage classes. In the compiler, it looks like enum in this context forwards to parse declaration, just like keywords such as pure, which can then find it is a function. If I'm reading this correctly, it does set the manifest constant flag, but otherwise just ignores it and indeed treats it the same as an auto return value. So nothing special, arguably just the parser not throwing an error when it perhaps could. It would be cool if it was a compile time value though. That way you could make sure code generating ctfe's were never included in the binary.
Re: Nobody understands templates?
On Sunday, 2 March 2014 at 11:47:39 UTC, Steve Teale wrote: On Sunday, 2 March 2014 at 10:05:05 UTC, Dicebot wrote: There is nothing wrong about not using templates. Almost any compile-time design can be moved to run-time and expressed in more common OOP form. And using tool you have mastery of is usually more beneficial in practice than following the hype. Yes DB, we can soldier on happily, but it would not do any harm to understand templates. The documentation examples quickly make your eyes glaze over, looking at the code in Phobos is doubtless instructive, but you can wade through a lot of that without finding what you want. Also I discovered an interesting fact today. the word 'mixin' does not appear in the language reference Templates section of dlang.org. It should be used in at least one example. I just discovered by trial and error that I could use 'mixin' in Templates (as opposed to Template Mixins), and when you know that it seems likely that you can accomplish lots of stuff you couldn't before. While I'm here, has anyone discovered a way to fudge a constructor super(..) call in a mixin template that's included in a class constructor. Since the mixin template is evaluated in the scope of the constructor, it seems like it should be OK. I'm sure I'll get there in time ;=) Steve You've got to learn to think a bit more abstractly. Templates are generalizations of things. Suppose I want to add two numbers using a function. int add(int, int)? double add(double, int)? float add(float, int)? char add(char, double)? etc which one? Do you want to have to create a function every time for every time? Whats the only significant difference between all of them? If you can't answer this then you can't abstract and which is the reason you don't understand templates. I could use one template function to handle all those cases above. That's what makes it powerful. I can basically write one function when you have to write 8, 10, 20 or whatever. S add(S, T)(S a, T b) { return cast(S)(a + b); } The compiler then generates all the concrete use cases for me. (and using oop can make it more powerful, S and T could be vectors) As long as the first type has an binary addition operator on it that takes the second type it will work and the template will work without change. But you want to continue using the hold way. It is analogous to those that want to continue to write procedural code because they don't see the what oop has to offer. BTW, how did you learn oop? Did you understand it all perfectly by reading a book or did you learn best by writing code that used it? If you don't attempt to use templates, even in example code, you won't get it.
Re: Nobody understands templates?
On Monday, 3 March 2014 at 18:46:24 UTC, Chris wrote: On Monday, 3 March 2014 at 18:03:12 UTC, Frustrated wrote: On Sunday, 2 March 2014 at 11:47:39 UTC, Steve Teale wrote: On Sunday, 2 March 2014 at 10:05:05 UTC, Dicebot wrote: There is nothing wrong about not using templates. Almost any compile-time design can be moved to run-time and expressed in more common OOP form. And using tool you have mastery of is usually more beneficial in practice than following the hype. Yes DB, we can soldier on happily, but it would not do any harm to understand templates. The documentation examples quickly make your eyes glaze over, looking at the code in Phobos is doubtless instructive, but you can wade through a lot of that without finding what you want. Also I discovered an interesting fact today. the word 'mixin' does not appear in the language reference Templates section of dlang.org. It should be used in at least one example. I just discovered by trial and error that I could use 'mixin' in Templates (as opposed to Template Mixins), and when you know that it seems likely that you can accomplish lots of stuff you couldn't before. While I'm here, has anyone discovered a way to fudge a constructor super(..) call in a mixin template that's included in a class constructor. Since the mixin template is evaluated in the scope of the constructor, it seems like it should be OK. I'm sure I'll get there in time ;=) Steve You've got to learn to think a bit more abstractly. Templates are generalizations of things. I think the problem is not that people don't understand templates in the sense that they are abstractions. The question is whether there are loads and loads of use cases for them. It is irrelevant if there are loads and loads of use cases for them. Just because people don't use something doesn't mean it is useless. Suppose I want to add two numbers using a function. int add(int, int)? double add(double, int)? float add(float, int)? char add(char, double)? etc which one? Do you want to have to create a function every time for every time? This is a typical use case and always mentioned in tutorials. The question is how many of these typical cases one encounters while writing software. Look at the STL library if you do't believe templates are useful... I think another problem with templates is that it is not always clear what is abstracted. The type or the logic? Both? In the above example the logic remains the same and is reproduced by the compiler for each type. Sometimes the logic can be abstracted for which type independence is important. But I'm not sure if that can be called a template in the purest sense. E.g. an algorithm that finds the first instance of something might be different for each type (string, char, int) and the abstract implementation has to differentiate internally (if string else if int else if ...). But this is no longer a template, or is it? Both logic and types are abtracted. Even though the template might use the same operator, the compiler must determine which concrete operator to use. The addition between the two abstract objects also requires an abstract operator. The great thing is, because the abstract logic is identical(adding two things) makes the template actually useful. If it wasn't we would have to specialize the template for all the different possible binary combinations and then it would defeat the simplification that abstract is suppose to offer. The the logical process is used when one looks at procedural code and realizes that one can simplify it by using oop. Templates give you the same power over oop that oop gives over non-oop. But just because templates[oop] are available doesn't mean you have to use it or it is always the best solution. I use templates all the time. I create them to simplify some task then put them in a library. For me, templates allow me to streamline things that I couldn't otherwise do. Any time I feel like something is being repeated a lot I automatically think that a templates will help. I hate copying and pasting and so I tend to use templates a lot. One of the main uses of templates is compile time type safety. This is necessary with oop because oop allows one to create types at compile time. Hence, the need to be able to make your oop safe is a natural step and templates help you accomplish that. e.g., Array's of objects vs Array's of a Type. One is much safer, informs the about what your intentions are so it can make better informed decisions. e.g., Array!Type allows the Array to determine if the Type supports certain things at **compile time**. Array!Object can't do this at compile time. If you can't see the benefit of Array!Type vs Array!Object then you are beyond help. (this is not to say Array!Object is always useless, but it is the most generic you can get and the compiler can do little to help the situation) I'll give you
Re: Nobody understands templates?
On Friday, 28 February 2014 at 18:42:57 UTC, Steve Teale wrote: All the D aficionados seem to wet their pants over meta-programming, but I struggle to find a place to use it. IIRC, I used it in a couple of places when I was trying to write library stuff for MySQL, but in my current project, I use it only once. That's when I want to stuff something onto my undo stack. For that I have two template functions - push(T)(MybaseClass* p, T t, int ID), and pushC, which is just the same except that it checks the top of the stack to see if the ID there is the same as what it is wanting to push. This has served me very reliably, but I struggle to find other places in the whole application where I would benefit from templates. Is this typical - libraries use templates, applications don't, or am I just being unimaginative? Yes. Templates are awesome. I use them when ever I can. They allow you to simplify the tasks. If you check out my thread about dependencies you can see a good example. iGui --iButton | | | WindowsGui --WindowsButton | | LinuxGui --LinuxButton When programming to interfaces you lose the ability to use concrete types easily. E.g., WindowsGui can't use a WindowsButton because it has to implement iGui, which uses iButton... even though WindowsButton is an iButton and the only one we want to use with WindowsGui. But as far as WindowsGui is concerned, there is no iButton but just a WindowsButton(Because it doesn't care about being general... and doesn't care about LinuxButton, RogueButton, or whatever). In some sense, iButton was meant to be used with iGui and WindowsButton for WindowsGui... but we can't do this easily in D... well, unless you use a template to generate all the crap code you would normally have to write. So a template(compile time construction) can help do things easier than you could otherwise... and if you do them right they are generic enough to be used in general things. (like anyone could use the template I created to help them with the same type of problem) You are missing the point because the whole reason templates are generally used in libraries is because they are so powerful(you want to reuse them). In the example I give above, the mixin template reduces code bloat and error proneness significantly for large classes and makes you feel like you are writing classes like you would normally write them when not using interface programming. Basically until you start using templates a lot you won't know where to use them in the first place. You just gotta get used to them and then you'll start trying to use them everywhere. (granted, I'm using mixin templates but templates nonetheless)
Runtime dependency checking
http://dpaste.dzfl.pl/80c6225ed090 The code above demonstrates run-time contracts using interface based programming. It provides two co-benfits: Simplified class implementation(you do not have to use interfaces for types which then requires casting that type for orthogonal behavior) and run-time contracts. e.g., The WindowsGui class is implemented using WindowsButton and not iButton. This allows one to avoid having to cast the iButton to a WindowsButton when one wants to use the featuers of a WindowsButton. A contract is created that every iButton used in WindowsGui must be a WindowsButton or an error is thrown. This creates a run-time contract or dependency between WindowsGui and WindowsButton. Normally in such interface based programming the contract is not automatic and any iButton(for example, a linux button) could be used for the WindowsGui. Normally this is not desired behavior as it limits what WindowsGui can do. Basically when we lift a class to an interface and any objects used in that class to interfaces we create contract that is in general too generic(but easier to specify in the language). This creates generally creates a problem for the implementations of the interface by forcing them to be more generic than one wants. To solve this requires casting and type checking to get the more specific type. The mixin attempts to automate this. It would be nice if the language was extended to allow covariance on argument types, e.g., interface iGui { @property T button(T : iButton)(T button); // Syntax says that any T can be used as long as it is derived from iButton(instead of just an iButton) } class WindowsGui : iGui { @property WindowsButton button(WindowsButton button) { } // implements the iGui.button property since it satisfies the contract and also allows us to use the type we actually want to use. (no explicit casts or checks) } Now, WindowsGui.button might be used with an iButton, so an implicit check is required to make sure that iButton is of WindowsButton type. The compiler could handle this quite easily. The mixin emulates such a feature. The mixin is not robust though. I seriously doubt that we'll ever get the semantics to handle this though. In any case, I think there is real benefit here and it makes it easier to do modular programming in D with proper dependency checking(WindowsGui is dependent on WindowsButton, not iButton or LinuxButton and this dependency is retained even when we use the iGui and iButton interface). Now, in the meantime I'll work on tidying up the mixin code but I was thinking about adding versioning. I could have a version property in all the types only if the versions have the same major version are they compatible. So a WindowsGui 3.42 is not compatible with a WindowsButton 2.89. Not sure if this a good way or if it will cause headaches later on. (I could keep a file of all the version compatibilities but that seems excessive) Any ideas? output Trying WindowsButton with WindowsGui! Do(): WindowsButton WindowsButton.foo(): I'm an extra WindowsButton feature! ...WindowsButton works in WindowsGui! Trying WindowsBorder with WindowsGui! Do(): WindowsBorder WindowsBorder.foo(): I'm an extra WindowsBorder feature! ...WindowsBorder works in WindowsGui! Trying LinuxBorder with WindowsGui! Invalid object type dependency mismatch! Type: f872.LinuxBorder Type Expected: WindowsBorder Trying LinuxButton with WindowsGui! Invalid object type dependency mismatch! Type: f872.LinuxButton Type Expected: WindowsButton Trying WindowsButton with LinuxGui! Invalid object type dependency mismatch! Type: f872.WindowsButton Type Expected: LinuxButton Trying LinuxButton with LinuxGui! Do(): LinuxButton ...LinuxButton works in LinuxGui! Trying WindowsBorder with LinuxGui! Invalid object type dependency mismatch! Type: f872.WindowsBorder Type Expected: LinuxBorder Trying LinuxBorder with LinuxGui! Do(): LinuxBorder ...LinuxBorder works in LinuxGui!
Programming to Interfaces simplification
http://dpaste.dzfl.pl/c25655e2dfe9 The code above simplifies using interfaces as the programming object. It allows one to program the derived classes as if they were not part of an abstraction by mapping the abstracted virtual methods to concrete methods. e.g., class WindowsGui : iGui { WindowsButton _button; @property WindowsButton button(WindowsButton b) { return (_button = b); } mixin(Fixup!(WindowsGui, iButton, WindowsButton)); } instead of class WindowsGui : iGui { WindowsButton _button; @property iButton button(iButton b) { assert(cast(WindowsButton)b !is null, `Invalid object type dependency mismatch! Type: `~b.classinfo.name~` Type Expected: WindowsButton`); auto bb = cast(WindowsButton)b; // do work with bb. } } (note the check and the cast are required for all usages of iButton if one wants to treat it as a WindowsButton. By using the mix, no checks and no casts are required. Much cleaner looking and less verbose code results, which is the whole point.) One problem with the template is that b.classinfo.name returns the interface instead of the actual class. In the example on dpaste, b.classinfo.name returns iButton, the base interface of LinuxButton. I want to display the actual class name that causes the problem(LinuxButton trying to be used where a WindowsButton goes). Obviously the Fixup template is not robust nor optimized for all cases but should handle most.
Re: Programming to Interfaces simplification
On Monday, 24 February 2014 at 18:59:32 UTC, Steven Schveighoffer wrote: On Mon, 24 Feb 2014 11:36:50 -0500, Frustrated c1514...@drdrb.com wrote: http://dpaste.dzfl.pl/c25655e2dfe9 The code above simplifies using interfaces as the programming object. It allows one to program the derived classes as if they were not part of an abstraction by mapping the abstracted virtual methods to concrete methods. e.g., class WindowsGui : iGui { WindowsButton _button; @property WindowsButton button(WindowsButton b) { return (_button = b); } mixin(Fixup!(WindowsGui, iButton, WindowsButton)); } instead of class WindowsGui : iGui { WindowsButton _button; @property iButton button(iButton b) { assert(cast(WindowsButton)b !is null, `Invalid object type dependency mismatch! Type: `~b.classinfo.name~` Type Expected: WindowsButton`); auto bb = cast(WindowsButton)b; // do work with bb. } } Nice work! One problem with the template is that b.classinfo.name returns the interface instead of the actual class. Hm... classinfo (now typeid) should get the most derived type from an instance. This may be a factor of it being an interface instance vs. a class instance. A simple test: Stevens-MacBook-Pro:~ steves$ cat testinterface.d import std.stdio; interface I { } class C : I { } void main() { I i = new C; writeln(typeid(i).name); writeln(typeid(cast(Object)i).name); } Stevens-MacBook-Pro:~ steves$ ./testinterface testinterface.I testinterface.C Looks like that is the case. Note that classinfo is not part of the language any more, and will likely be deprecated. typeid is the correct mechanism to get the TypeInfo of a derived class. I'm thinking this is incorrect, typeid should get the derived class type IMO. It shouldn't be that difficult or costly for the compiler to do. Thanks. Now the correct type is known. One could, for example, look for wrappers/adapters/etc to get a linuxbutton into a windowsbutton(if so desired, throw a well informed error, etc. Hopefully though, now you see the point. It is a runtime contract that you make since you can't specify it at compile time(since D doesn't supports it). In any case the mixin needs some work and testing. Would just like to get the proper class name for the type. It is, at the very least, a proof of concept. Unfortunately the main downside is the vtable is twice as big. Final or static methods could be used for this. If the compiler could manage such a system it could do the job better. (There would be no extra functions needed and the calls would be faster) The issue is this: I want to program to interfaces(requiring the class(WindowsGui) to use base interfaces(iButton) to satisfy the interface. The problem is this compile time contract is to generic and makes coding the classes more verbose. The mixin reduces the verbosity and provides a runtime contract(we enforce it using asserts in this case). The benefit of the mixin is that coding WindowsGui is simpler and more direct and it's dependency on WindowsButton(not iButton) is known at compile time(But enforced at runtime by assert). Would you not agree? Everything else is essentially identical.
Re: Programming to Interfaces simplification
Fixed code with all combination examples: (again, only WindowsButton works with WindowsGui and same for LinuxGui... but the classes don't use iButton like they should!!! Oh, they break the contract!! End of the world!) http://dpaste.dzfl.pl/02ee45225303 Output: Trying WindowsButton with WindowsGui! Do(): WindowsButton WindowsButton.foo(): I'm an extra WindowsButton feature! ...WindowsButton works in WindowsGui! Trying LinuxButton with WindowsGui! Invalid object type dependency mismatch! Type: f324.LinuxButton Type Expected: WindowsButton Trying WindowsButton with LinuxGui! Invalid object type dependency mismatch! Type: f324.WindowsButton Type Expected: LinuxButton Trying LinuxButton with LinuxGui! Do(): LinuxButton ...LinuxButton works in LinuxGui!
Re: Cannot implicitly convert derived type
On Sunday, 23 February 2014 at 01:37:08 UTC, Steven Schveighoffer wrote: On Sat, 22 Feb 2014 15:17:37 -0500, Frustrated c1514...@drdrb.com wrote: It is legal exactly because I will always guarantee that the proper button will be used. Static typing says it's not legal. D does not do dynamic type checking upon calling virtual functions. It is not logically legal as mentioned several times... no one needs to mention that. But it is legal within the context of the code. I'll never use a RogueButton so why force me to code for the chance I might? You may not be the only one using WindowsGui. You can't guarantee other code won't do it. In any case, the compiler cannot possibly know your intentions. Basically, the point is, the compiler could enforce the above but make the code more readable. e.g., I do this: @property WindowsButton button(WindowsButton b) { } The compiler turns this into @property WindowsButton button(iButton _b) { if (is(_b : WindowsButton)) assert(0, Rogue button used); auto b = cast(WindowsButton)_b; } This solution is not as efficient as the one I outlined. If you have a WindowsGui object, no need to accept iButton when you require WindowsButton. One allows me to program in a natural way while the other makes me jump through hoops which litters the code with a bunch of casts and checks which are only there in the odd event that I assign the wrong type(which, I'm not going to do on purpose). Sorry, if you want a dynamically typed language, use one. D is not that. Again, the whole point of why it is illegal because you can pass a RogueButton... BUT I DON'T INTEND TO PASS THEM! If I could absolutely guarantee that I won't pass them then there should be no problem(no asserts). Since I can't guarantee it I have to litter my code with checks? The compiler could do this for me. You can't guarantee it. That is the point. The compiler could do the checks for you, but D is not dynamically typed. The best you can do is encapsulate the type checking code as a mixin. -Steve It has nothing to do with being dynamically typed. We can't solve this problem until you get your head out of the gutter(the gutter being how D does things already. Can't make progress on something if you ever look beyond what it can do). This has to do with simply adding checks to enforce the type. I can guarantee it, but like you said, I can't guarantee what others do. Hence the check. The fact is, I presented two versions of the code. One represents the other. It is a representational problem, nothing more, nothing less. Please understand that from now on. e.g., a switch statement is just a representational form of if statements to simplify. I'll I'm talking about is adding a switch statement. (if you take that literal and can't see how it relates to the original problem then you are completely missing the point of the whole discussion) I did think it might be possible to use CT reflection to generate all the type checking automatically but this might be difficult and would have to generate a new class. It seems like the only way to get at this problem in D.
loop over all parameters of all overloads of all members
The following code craps out on the inner for each foreach (am; __traits(derivedMembers, B)) foreach (m; [__traits(getOverloads, B, am)]) { } So how can I loop over all the parameters of all the overloads of all the members of a class? Create some weird mapping tuple? I guess we are not going to get a static foreach any time soon?
Re: Cannot implicitly convert derived type
On Sunday, 23 February 2014 at 20:41:30 UTC, Jesse Phillips wrote: On Saturday, 22 February 2014 at 20:17:37 UTC, Frustrated wrote: I do this: @property WindowsButton button(WindowsButton b) { } The compiler turns this into @property WindowsButton button(iButton _b) { if (is(_b : WindowsButton)) assert(0, Rogue button used); auto b = cast(WindowsButton)_b; } Why does your WindowsGui violate the iGui contract? It doesn't. It simply that one can't specify dependencies in D if (iGui is WindowsGui) then iButton is WindowsButton; It's not very hard logic but people are not even trying. I am attempting to make a mixin to solve the problem. The mixin will simply overload all methods in the derived class(WindowsGui) and when WindowsButton is used it will create an overload using iButton(to satisfy the interface) with the check to make sure the iButton is a WindowsButton. It will give me what I want except I have to create the mixin and then insert it in all the classes. (In theory though it should not add any overhead is used where it is not suppose to) But unfortunately when I try to find all members that use WindowsButton(or whatever) to be able to create the new overload, I get error due to the inner foreach. foreach (am; __traits(derivedMembers, B)) foreach (m; [__traits(getOverloads, B, am)]) { // check if method contains an parameter of type WindowsButton, then create identical method definition that uses iButton instead. Put a check in the method and call this method using a cast. This essentially overrides the virtual method satisfying the interface but passes the work to the user defined method. } What the above code will do, when working, is create the verbose code you quoted from the first case: @property WindowsButton button(WindowsButton b) { } The ***mixin*** turns **ADDS** this @property WindowsButton button(iButton _b) { if (is(_b : WindowsButton)) assert(0, Rogue button used); auto b = cast(WindowsButton)_b; button(b); // Call the user defined function here(hopefully) }
Re: Cannot implicitly convert derived type
On Sunday, 23 February 2014 at 23:14:24 UTC, Jesse Phillips wrote: On Sunday, 23 February 2014 at 21:06:03 UTC, Frustrated wrote: Why does your WindowsGui violate the iGui contract? It doesn't. It simply that one can't specify dependencies in D if (iGui is WindowsGui) then iButton is WindowsButton; It's not very hard logic but people are not even trying. I understand what you intend your code to do, but that is still breaking the contract which you setup. iGui takes an iButton because you defined it that way, to only handle specific types of iButton is a breach of contract. The language lets you break contracts, but it should not help you do so. Nope. It has nothing to do with the contract. You are totally missing the point. It is all about reducing typing a bunch of extra shit. Don't know why you can't see that. In any case once I get the mixin in finish it will do what I want and be good enough. IF the damn language had the ability to specify dependencies then it wouldn't be a problem. Just because you insist on using D's current model as the only model you will always be right... I hope that makes you happy. In the mean time I'll be moving on to writing cleaner code...
Re: Cannot implicitly convert derived type
On Saturday, 22 February 2014 at 01:03:22 UTC, Steven Schveighoffer wrote: On Fri, 21 Feb 2014 17:54:06 -0500, Frustrated c1514...@drdrb.com wrote: interface iGui { @property iButton button(ref iButton button); } class WindowsGui : iGui { WindowsButton _button; @property WindowsButton button(ref WindowsButton button) //@property iButton button(ref iButton button) { _button = button; return button; } } interface iButton { } class WindowsButton : iButton { } Should this not work? What you are trying to do is not legal. e.g.: class RogueButton : iButton { } iGui gui = new WindowsGui; gui.button = new RogueButton; Note that setting gui.button to any iButton is legal, but the derived type REQUIRES a WindowsButton. This would have to be rejected at runtime, because the compile-time type is implicitly convertible. There are two types of variance that are logical, contravariance and covariance. covariance allows you to *return* a more derived type than the base. In other words, this would be legal (assume same iButton/WindowsButton structure): interface iGui { @property iButton button(); } class WindowsGui : iGui { @property WindowsButton button() {...}; } This works, because whenever you return a WindowsButton, you ALSO are returning an iButton. In fact, D supports this. The opposite is contravariance, and that's used on *input* parameters. In this case, the derived method can accept a base of the parameter that the base class defines: interface iGui { void button(WindowsButton); // please humor me, I know you don't want to do this :) } class WindowsGui : iGui { void button(iButton); } This is logically sound, because the actual implementation only requires an iButton. Therefore, passing a WindowsButton into the iGui interface still satisfies that requirement. However, D does NOT support contravariance. 2. In the second case, I can cast to make everything work. This seems wrong. Hence goto 1. WindowsGui is designed to only work with WindowsButton, say, and I should never have to use iButton in the WindowsGui class unless, maybe, I want to support non-windows buttons in the WindowsGui for some reason. This is actually the correct mechanism if you want to use polymorphism. However, in some cases, a templated system may be more advantageous than an interface system. One other possibility is to use overloading -- i.e.: class WindowsGui { @property WindowsButton button(WindowsButton b) { return _button = b;} @property WindowsButton button(iButton b) { if(auto wb = cast(WindowsButton)b) button = wb; else throw new ButtonException; } } This is not really an attractive solution, but it could be easily generated as a mixed-in solution. -Steve It is legal exactly because I will always guarantee that the proper button will be used. It is not logically legal as mentioned several times... no one needs to mention that. But it is legal within the context of the code. I'll never use a RogueButton so why force me to code for the chance I might? Again, WindowsGui only uses WindowsButton which is a iButton type. So why force me to always use iButton and cast it to WindowsButton? Why can't I relax the condition to use the base type? The only reason it is illegal is because I could use a RogueButton, BUT I WON'T! If I do, then it is an error. Basically, the point is, the compiler could enforce the above but make the code more readable. e.g., I do this: @property WindowsButton button(WindowsButton b) { } The compiler turns this into @property WindowsButton button(iButton _b) { if (is(_b : WindowsButton)) assert(0, Rogue button used); auto b = cast(WindowsButton)_b; } One is very clean, the other is not. If by chance I use the wrong button(a Rogue button) then it results in an error(hopefully user controlled). One allows me to program in a natural way while the other makes me jump through hoops which litters the code with a bunch of casts and checks which are only there in the odd event that I assign the wrong type(which, I'm not going to do on purpose). Again, the whole point of why it is illegal because you can pass a RogueButton... BUT I DON'T INTEND TO PASS THEM! If I could absolutely guarantee that I won't pass them then there should be no problem(no asserts). Since I can't guarantee it I have to litter my code with checks? The compiler could do this for me.
Re: Cannot implicitly convert derived type
On Saturday, 22 February 2014 at 05:20:25 UTC, Eric Suen wrote: Generic? I don't see how this would help. I'd have to specify every concrete type in the creation of the object which might be significant. I can't use a generic virtual method so that doesn't help either. It would be nice to have something like T foo(T : iButton)(T button); Which then I override with WindowsButton foo(WindowsButton button) { } Since WindowsButton is derived from iButton. The compiler would have to insert a type check to make sure when I called the first one(from the interface) that it was a windows button that was passed(since any iButton could be passed) when using the WindowsGui. The main point of all this is simply efficiency. I have to liter the code with checks and casts when it is entirely possible to get the compiler to automate it all. By doing so one can program the concrete class in a much more natural way.
Cannot implicitly convert derived type
interface iGui { @property iButton button(ref iButton button); } class WindowsGui : iGui { WindowsButton _button; @property WindowsButton button(ref WindowsButton button) //@property iButton button(ref iButton button) { _button = button; return button; } } interface iButton { } class WindowsButton : iButton { } Should this not work? Error: class main.WindowsGui interface function 'iButton button(ref iButton button) @property' is not implemented Or by using the commented line: Error: cannot implicitly convert expression (button) of type main.iButton to main.WindowsButton 1. In the first case I override a property using a more derived type. This should work but doesn't. Seems D doens't support covariance properly? 2. In the second case, I can cast to make everything work. This seems wrong. Hence goto 1. WindowsGui is designed to only work with WindowsButton, say, and I should never have to use iButton in the WindowsGui class unless, maybe, I want to support non-windows buttons in the WindowsGui for some reason. Basically, because of the covariance issue I end up having to use a lot of casts. Hopefully theres some simple trick that won't pollute the code to make this work. I guess I could use a templated property with a generic type that is derivable from iButton to make it work? In some sense I can understand the error. If I'm using iGui then I have the option to use any button(since it is generic) but if iGui is a WindowsGui I'm not allowing this. The issue is, that I will have some type of dependency restrictions on the types. e.g., iGui g = new WindowsGui; g.button = new LinuxButton; // ok but not ok!! (should result in an error in some way) Obviously I can cast and check the type and do all that. Just feels like the wrong way to go about it because it requires a lot of casting and polluting the code with checks that in general, should be unnecessary. Again: In the WindowsGui I want to use WindowsButton, not iButton because WindowsGui will never need any other type of button. iButton is too general to use in WindowsGui. (it would be cool if one could do something like class WindowsGui : iGui iButton = WindowsButton // constrains iButton to always be a WindowsButton. Checks/casts are automatically added by compiler when necessary { // use WindowsButton here with proper covariance relations and checks/casts } Anyways, hopefully there is some single trick to get what I'm asking?
Re: Cannot implicitly convert derived type
On Friday, 21 February 2014 at 23:19:19 UTC, Ali Çehreli wrote: On 02/21/2014 02:54 PM, Frustrated wrote: interface iGui { @property iButton button(ref iButton button); } class WindowsGui : iGui { WindowsButton _button; @property WindowsButton button(ref WindowsButton button) //@property iButton button(ref iButton button) { _button = button; return button; } } interface iButton { } class WindowsButton : iButton { } Should this not work? Error: class main.WindowsGui interface function 'iButton button(ref iButton button) @property' is not implemented Or by using the commented line: Error: cannot implicitly convert expression (button) of type main.iButton to main.WindowsButton 1. In the first case I override a property using a more derived type. This should work but doesn't. Seems D doens't support covariance properly? 2. In the second case, I can cast to make everything work. This seems wrong. Hence goto 1. WindowsGui is designed to only work with WindowsButton, say, and I should never have to use iButton in the WindowsGui class unless, maybe, I want to support non-windows buttons in the WindowsGui for some reason. Basically, because of the covariance issue I end up having to use a lot of casts. Hopefully theres some simple trick that won't pollute the code to make this work. I guess I could use a templated property with a generic type that is derivable from iButton to make it work? In some sense I can understand the error. If I'm using iGui then I have the option to use any button(since it is generic) but if iGui is a WindowsGui I'm not allowing this. The issue is, that I will have some type of dependency restrictions on the types. e.g., iGui g = new WindowsGui; g.button = new LinuxButton; // ok but not ok!! (should result in an error in some way) Obviously I can cast and check the type and do all that. Just feels like the wrong way to go about it because it requires a lot of casting and polluting the code with checks that in general, should be unnecessary. Again: In the WindowsGui I want to use WindowsButton, not iButton because WindowsGui will never need any other type of button. iButton is too general to use in WindowsGui. (it would be cool if one could do something like class WindowsGui : iGui iButton = WindowsButton // constrains iButton to always be a WindowsButton. Checks/casts are automatically added by compiler when necessary { // use WindowsButton here with proper covariance relations and checks/casts } Anyways, hopefully there is some single trick to get what I'm asking? It should not work because the derived type is requiring more than the interface. iGui requires that the parameter to button() is iButton: @property iButton button(ref iButton button); However, WindowsGui is bringing an extra requirement by asking a more specific iButton: @property WindowsButton button(ref WindowsButton button) Note that there is no problem with the return type because this time the derived type is still returning an iButton because WindowsButton is an iButton. I don't know whether this works for you but I made the actual button a constructor parameter: interface iGui { @property iButton button(); } class WindowsGui : iGui { WindowsButton _button; // The constructor gets the button this(WindowsButton button) { this._button = button; } @property WindowsButton button() { return _button; } } interface iButton { } class WindowsButton : iButton { } void main() { auto w = new WindowsGui(new WindowsButton()); w.button; } Ali But what about a setter? Using DI isn't the way to go here. The point that in the windows class, it will only ever use a windows button. This is fine, but because I'm using iGui(programming to interfaces), it causes a problem inside the windows class, which it shouldn't. e.g., if I only had one gui and used one class, then there would never be a problem. Also, it is not a problem of construct, I already have a solution by casting. But casting hides the fact that windowsgui is meant to use only a windows button... which is obvious in the design. Again iGui uses an iButton WindowsGui uses a WindowsButton But when iGui is an actual WindowsGui, it forces WindowsGui to be more generic than it is meant to be. The key piece of information here is that I will only ever use WindowsButtons with WindowsGui... this fact is not general and the reason the compiler throws the error BUT it is always the case in my code(except in errors). I need to inform the compiler that it is always the case and then I can do what I want.
Re: Container templates
On Wednesday, 19 February 2014 at 21:50:43 UTC, Meta wrote: On Wednesday, 19 February 2014 at 19:44:12 UTC, Meta wrote: On Wednesday, 19 February 2014 at 19:10:44 UTC, Frustrated wrote: Are there container templates that one can mixin to classes that give them container behavior? e.g., instead of class A { Array!int x; } I want class A { mixin Array!int; } so that I can do something like a.Add(3) instead of a.x.Add(3). One solution is to use alias this. class A { Array!int x; alias x this; } Then you can do a.Add(3) and the method call will be rewritten (I don't know if it's *actually* rewritten) as a.x.Add(3). myints nor myfloats need to be actual elements of the class. In fact, in this case it might be ok to override them, e.g., a.add(1) and a.add(5f) above. This throws a wrench into the above solution, as you can currently only have 1 alias this. However, your idea of inner classes would work, I think. I played around with it a bit at work and this is a workable solution: import std.container; class A { this() { myints = new MyInts(); myfloats = new MyFloats(); } MyInts myints; MyFloats myfloats; private static { class MyInts { Array!int x; alias x this; } class MyFloats { Array!float x; alias x this; } } } void main() { auto a = new A(); a.myints.insert(3); a.myfloats.insert(3); } This should work. Just have to add the overrides and call the base function(e.g., override insert and then call x's insert). This at least gets the job done... I wonder if there is a better way?
Container templates
Are there container templates that one can mixin to classes that give them container behavior? e.g., instead of class A { Array!int x; } I want class A { mixin Array!int; } so that I can do something like a.Add(3) instead of a.x.Add(3). In fact, I do want the first case because I will have multiple arrays and need a way to add separation between them(the x does that here) BUT the real problem is I need to hook into the add, remove, etc to do things like validate. e.g., programming challenge: Create a class that contains two different arrays of type int and type float that will restrict the int's to a range of 3 to 10 and print a msg to the consol when a float larger than 1 is added or removed from the float array. a.myints.add(1); // asserts a.myfloats.add(5); // prints msg to console myints nor myfloats need to be actual elements of the class. In fact, in this case it might be ok to override them, e.g., a.add(1) and a.add(5f) above. The goal here is to do this in the minimum amount of work. I don't want to have to recreate the array code every time I use them in the class... and I don't want to inherit from a class or use DI. e.g., templates should be the way to go. Just not sure how to make it all work and if there are templates that work this way(allow hooking into the methods). I thought about using inner classes to add the separation: class a { class myints // : Array!int { mixin Array!int; // override void Add(int i) {} } } which I guess would work better if myints was a template. Any ideas?
Re: Container templates
On Wednesday, 19 February 2014 at 19:44:12 UTC, Meta wrote: On Wednesday, 19 February 2014 at 19:10:44 UTC, Frustrated wrote: Are there container templates that one can mixin to classes that give them container behavior? e.g., instead of class A { Array!int x; } I want class A { mixin Array!int; } so that I can do something like a.Add(3) instead of a.x.Add(3). One solution is to use alias this. class A { Array!int x; alias x this; } Then you can do a.Add(3) and the method call will be rewritten (I don't know if it's *actually* rewritten) as a.x.Add(3). myints nor myfloats need to be actual elements of the class. In fact, in this case it might be ok to override them, e.g., a.add(1) and a.add(5f) above. This throws a wrench into the above solution, as you can currently only have 1 alias this. However, your idea of inner classes would work, I think. yeah, I basically want to avoid typing a lot and reuse code. I could create a template that is essentially all the code from your standard container object(probably just rename class to template) and mix it in. The problem is that there will be a lot of methods in the class... probably not a real issue. I could use the types directly. Not sure, though, the benefit of using templates over inheritance/inner classes. Just trying to avoid a lot of typing and have an efficient solution. I have several classes with array inside them and I want to convert them so that I can add hooks later(do stuff when elements are added/etc easily... without the overhead of delegates or events that one might normally use for RT behavior). templates seem like the solution but now sure if there such an array/container already exists so I can plug and play.
Re: Circular Buffer
On Monday, 10 February 2014 at 10:41:06 UTC, Russel Winder wrote: On Mon, 2014-02-10 at 09:16 +, Gary Willoughby wrote: On Monday, 10 February 2014 at 03:14:31 UTC, Jonathan Dunlap wrote: (disclaimer: I'm new around here) Is it possible to cycle backwards? If not, what's the best approach? import std.algorithm; import std.array; import std.range; import std.stdio; void main(string[] args) { auto data = [1,2,3]; assert(data.cycle.take(5).array == [1,2,3,1,2]); assert(data.retro.cycle.take(5).array == [3,2,1,3,2]); } This is why people should be using D instead of C++! This really needs to get onto the D website somewhere. how efficient is ufcs? It seems like it would be very slow in general and way better to manually do the code. I wonder if anyone has done any tests?
Re: std.random.uniform for enums
On Thursday, 13 February 2014 at 02:14:02 UTC, Jakob Ovrum wrote: On Thursday, 13 February 2014 at 02:02:38 UTC, Anton wrote: I'm confused about how to use random.uniform to select a member of an enum. Say I have an enum like enum Animals { cat = 0, dog = 1, chimpanzee = 2 } I want to select a random animal. So far I've been trying to do uniform(Animals), but every time I try to compile that, I get a does not match any function template declaration error. Am I misunderstanding how this function is meant to be used? The problem with using `uniform` for enums is that not all enums are sequential without holes, which would make the `uniform` implementation quite non-trivial if it were to try to handle enums generically. If you know your enum is sequential and doesn't have any holes, assume responsibility for that fact with a cast: --- enum Animals { cat = 0, dog = 1, chimpanzee = 2 } void main() { import std.random, std.stdio; foreach(immutable _; 0 .. 10) writeln(cast(Animals)uniform![](Animals.min, Animals.max)); } --- Could you not simply select one at random by name? Even though the values of the enum may not be sequential the keys are.
Re: Templated static opCall in non-templated struct
On Tuesday, 11 February 2014 at 00:00:06 UTC, Matthew Dudley wrote: Here's the gist of what I'm trying to do: struct Foo { public: int i; int j; static opCall(int i)(int j, int k) { return Foo(i+j,i+k); } } void main() { auto bob = Foo!(1)(2,3); //Error: template instance Foo!1 Foo is not a template declaration, it is a struct } I'm trying to template the static opCall function, not the struct. Is there a way to do disambiguate between the two? You can't do this! you are calling Foo as if it is a template... hence the error! Maybe the only solution is a new symbol such as Foo!!(1)(2,3) where !! tells the compiler that you are referencing an implicit function call and not a template. Would be an easy solution.
Re: How to call opCall as template?
On Friday, 31 January 2014 at 00:29:20 UTC, Namespace wrote: On Thursday, 30 January 2014 at 22:34:52 UTC, Frustrated wrote: On Thursday, 30 January 2014 at 21:33:09 UTC, Namespace wrote: I think for your example, the first case works fine using deduction. Sure but this is not always possible. ;) It seems that the problem occurs also with opIndex and so probably with all op* methods. See: http://forum.dlang.org/thread/bug-1204...@https.d.puremagic.com%2Fissues%2F#post-lcegar:241ld2:241:40digitalmars.com Yes, because they all are implicit. It looks like you are calling a template. D could figure this out but I think it will end up having similar issues as has in C++. Is it an a templated op* on an object or is it template function call? Explan it please with examples. I'm convinced that D is smarter as C++ with the '' problem. --- class Foo { void opCall(size_t count) { } } Foo f = new Foo(); f(42); /// no template class Foo { void opCall(T)(size_t count) { } } Foo f = new Foo(); f!int(42); /// template No ambiguity. As far as I understand you, you mean something like this: import std.stdio; class Foo { void opCall(size_t count) { writeln(F()); } } void f(T)(size_t count) { writeln(f()); } void main() { Foo f = new Foo(); f(42); } which prints correctly F() no, f(42) is not a template call and f!(42) is not ambiguous because opCall is not templated. So no ambiguity here. But if you have class Foo { void opCall(T)(size_t count) { writeln(F()); } } then do f!(42); AND had the notation you wanted to use earlier. then which f is to be called? is f!(string)(42) referring to the templates opCall? OR is f!(string)(42) calling the template(which it normally would)? The point being there can be no unambiguous way to use the template call notation with a templated opCall if the template parameter must be explicitly given. If it can be deduced then it's call looks like a normal function call and no ! is needed, and then no ambiguity. C++ had the issues where it crapped out on . When used in template calls, say two nested ones), one would end up with , which the compiler would think it was a left shift operation and not part of the template. One would always have to put a space between them to make the templates work properly. This has been recently fixed. Somewhere on the D site, Walter(I guess) explains that he chose to use ! for template call syntax because it is not used anywhere else in any ambiguous way so when you see a template call YOU know it is a template call, unambiguously. So it becomes easy to deal with semantically. So, if your notation was implemented, it would no longer be easy to know. The compiler would have to be context sensitive, which is more complex and not perfect. I doubt Walter would go for that so you'll never be able to use an explicit templated opCall... but implicit are ok.
Re: How to call opCall as template?
On Friday, 31 January 2014 at 10:31:52 UTC, Namespace wrote: So, if your notation was implemented, it would no longer be easy to know. The compiler would have to be context sensitive, which is more complex and not perfect. I doubt Walter would go for that so you'll never be able to use an explicit templated opCall... but implicit are ok. I never wanted a new notation. I only want that the bug gets fixed. :) Wow, that is the point! it's not a bug! You are asking for a new notation. In your post you did F f; int i = f(3,4,5); float f_ = f!float(6, 7, 8); f is an object!!! not a template, you are calling opCall on it, right? (the last line) BUT THAT SYNTAX IS FOR TEMPLATES ONLY!!! Do you not see that if I add template f(T) { T f(int x, int y, int z) { return 3.14; } } that there is no way the compiler can know what you mean now? (again, assuming your bug was fixed) PAY ATTENTION!!! The following is your code with the added template I gave and two lines of yours commented out! import std.stdio; struct F { T opCall(T = int)(int a, int b, int c) { return cast(T)(a * b * c); } } void main() { //F f; //int i = f(3,4,5); float f_ = f!float(6, 7, 8); } template f(T) { T f(int x, int y, int z) { return 3.14; } } NOTE TO YOURSELF!! IT COMPILES JUST FINE I didn't change a damn thing! I'm not playing tricks or anything. the float f_ line is exactly what you gave, YET I MADE IT COMPILE WITH OUT YOUR STRUCT!!! THIS MEANS IT IS AMBIGUOUS! Your struct or my template would make it work(again, assume you could actually do what you want). This means it is impossible for the compiler to know which one you meant if we uncommented the lines. The only way it would work is if one couldn't have variables and templates use the same name at the same time in the same scope but this already is possible and is not ambiguous. So to fix your bug could break the compiler in certain circumstances. will it do it in all circumstances, no. But I doubt Walter will go for it. Not only does it look like a template call(it is in the above example), it might be hard to parse and is ambiguous in some cases. Now, maybe there is a trick to make it all work using aliases and templates but that is not the point. The point is, that the is an ambiguity because you are using the EXACT same syntax for two different things. If you can't see that then I can't help you any further.
Re: mixin template
On Friday, 31 January 2014 at 06:26:16 UTC, Dan Killebrew wrote: On Friday, 31 January 2014 at 06:24:27 UTC, Dan Killebrew wrote: mixin template Foo(alias a){ alias Foo=a; } pragma(msg, Foo!2); // error template Bar(alias a){ alias Bar=a; } pragma(msg, Bar!2); // ok As far as I can tell, 'mixin template' does nothing new; (besides fail to compile in Timon's reply). I should have said it does nothing helpful. Using a mixin template forces it to be used as a mixin which, sometimes you need. It does something new because it is different. If you drop the mixin and use a template then it is a different construct than than a mixin template. e.g., template X() { static this() { } } mixin template Y() { static this() { } } class A { mixin X; } class B { mixin Y; } class C { X; // ok because X is a normal template } class D { Y; // error, Y has to be mixed in since it is a mixin template } A and B are the same. C compiles fine. D fails because we are using Y like it was a normal template function not it is not. We might want that because a mixin template and a template have different meanings. One mixes in the code on site and one doesn't. If you write a mixin template and it would fail if it were used as a template then you should make sure to use the mixin in front of it. One could argue that they should have been disjoint, i.e., a normal template should not be able to be mixed in and a mixin template must be mixined. This was not done. If you write a mixin template and it can't or shouldn't be used as a normal template, then use the 'mixin template'. This prevents it from being used as a normal template. If you write a normal template and do not want it to be mixed in, you are out of luck. Not sure if their was a good reason for this or not. (probably ok to use and in some cases very useful to have so it was made optional)
Re: How to call opCall as template?
Are you always so aggressive? :) Not always ;) Just when I feel like it
Reference parent type
Suppose I have class A { mixin t!A; } is there a way to replace the mixin template's dependence on the class name? e.g., class A { mixin t!This; // This turns in to A } (so, for example, renaming the above class only has to rename one place instead of two)
Interfaces allow member definitions?
I was, I think, able to call an interface's method. I had the code like the following interface A { void foo(); } class B : A { void foo() { writeln(Hey); } } class C : A { void foo() { writeln(You); } } yet, when I called a.foo(); I did not get any output. (A being of type A) Now, I was doing some weird stuff but either in the vtable for A, there are empty functions that do nothing or I just happen to call bogus memory that did not throw an exception. The real question is, do interface methods actually support function definitions? Is there anything that stops us from actually doing interface A { void foo() { writeln(What up!!); } } internally? I know member functions require a this but in this case foo does not require this so it any this would work. Basically, does the vtable contain storage for the interface's members but blocks us from using them due to the issue with this? If so, then shouldn't we be able to create functions in an interface as long as they do not reference this? (basically static functions that can be overriden as dynamic functions in the class) e.g., interface A { // default behavior for foo and bar void foo() { writeln(asdasdfasdfasdf); } void bar() { writeln(1234); } } class B : A { void foo() { writeln(help); } } void main() { A a = new B; a.foo(); // prints help a.bar(); // prints 1234 B b = new B; b.foo(); // prints help b.bar(); // prints 1234 } This would allow one to sort of add default behavior to an interface(limited since no fields could be used but properties help with it). basically the vtable just needs an extra spot for the interface methods and calls them with null or the object it contains for this... which doesn't matter since this is never used in the body of the function.
Re: Interfaces allow member definitions?
On Thursday, 30 January 2014 at 11:29:55 UTC, TheFlyingFiddle wrote: On Thursday, 30 January 2014 at 11:19:58 UTC, Frustrated wrote: I was, I think, able to call an interface's method. I had the code like the following interface A { void foo(); } class B : A { void foo() { writeln(Hey); } } class C : A { void foo() { writeln(You); } } yet, when I called a.foo(); I did not get any output. (A being of type A) Now, I was doing some weird stuff but either in the vtable for A, there are empty functions that do nothing or I just happen to call bogus memory that did not throw an exception. The real question is, do interface methods actually support function definitions? Is there anything that stops us from actually doing interface A { void foo() { writeln(What up!!); } } internally? I know member functions require a this but in this case foo does not require this so it any this would work. Basically, does the vtable contain storage for the interface's members but blocks us from using them due to the issue with this? If so, then shouldn't we be able to create functions in an interface as long as they do not reference this? (basically static functions that can be overriden as dynamic functions in the class) e.g., interface A { // default behavior for foo and bar void foo() { writeln(asdasdfasdfasdf); } void bar() { writeln(1234); } } class B : A { void foo() { writeln(help); } } void main() { A a = new B; a.foo(); // prints help a.bar(); // prints 1234 B b = new B; b.foo(); // prints help b.bar(); // prints 1234 } This would allow one to sort of add default behavior to an interface(limited since no fields could be used but properties help with it). basically the vtable just needs an extra spot for the interface methods and calls them with null or the object it contains for this... which doesn't matter since this is never used in the body of the function. You can already do this using the Non-virtual interface ideom interface Foo { final void bar() { writeln(Something); } void baz() { writeln(Something Else); } } Note the final keyword it is imortant here. This will make bar simply be a non-virutal method in Foo. If you want to provide some basic implementation but still forward to a base class you can do something like this. interface Foo2 { final void bar(uint i) { // Does some basic stuff here. bar_impl(i); } protected void bar_impl(uint i); } class A : Foo2 { protected void bar_impl(uint i) { //Do some specific stuff here. } } This pattern allows you to do some basic stuff in bar and more specialized stuff in bar_impl. It does require that you overload bar_impl though which may not be what you want. But this is not what I am talking about. Obviously one could use a multitude of ways to accomplish the same task but nothing is simple, direct, and elegant. Do you realize you have to define two functions in the interface? I'm not asking about a work around but if what I am talking about can actually be done(does the vtable support this or can made to support it?)
Re: How to call opCall as template?
On Thursday, 30 January 2014 at 16:28:42 UTC, Namespace wrote: On Thursday, 30 January 2014 at 16:24:00 UTC, Stanislav Blinov wrote: void main() { F f; int i = f(3,4,5); float f_ = f!float(6, 7, 8); } Does not work, it fails with: Error: template instance f!float f is not a template declaration, it is a variable f.opCall!float(6, 7, 8); ... Yes, of course. But where is the sense to use opCall if I need to call it explicitly? Could you not use opDispatch? Not sure if you can templatize it or not though...
Re: Interfaces allow member definitions?
On Thursday, 30 January 2014 at 15:28:24 UTC, Steven Schveighoffer wrote: On Thu, 30 Jan 2014 09:31:05 -0500, Frustrated c1514...@drdrb.com wrote: I'm not asking about a work around but if what I am talking about can actually be done(does the vtable support this or can made to support it?) Yes. Interfaces have no concrete vtable. Only classes do. A concrete class can decide what the vtable has in it, and if you had a default implementation, the compiler could stick that in there. Note that the default implementation only can call other member functions within the interface or module-level functions, interfaces cannot access any derived data or members. Whether such a change would be accepted? No clue. -Steve Basically I see no reason why the compiler can't treat the interface as a class and allow default methods. (it would have to allow multiple inheritance on that class though) All it would do is make it easy to provide a default implementation(more of a static implementation but allows it to be overriden, which makes it useful). For example, when creating a design you would no longer have to specifically create a corresponding class to use for the interface. You could just provide some default implementations of everything(throw errors, write stuff, etc...) I think it would be probably rather easy to do by extending the vtable to have one lower level, the interface methods, which, in fact, could use this(so you could have a this in them but only reference other members of the interface). Essentially what it boils down to is treating interfaces like classes that have no fields). To avoid the diamond problem simply always choose the method that is not from the interface(since it is default), which is done naturally with the vtable. Of course, maybe this just creates the diamond problem for interfaces: which default implementation to use... which I'm not sure if it's a problem?
Re: Interfaces allow member definitions?
On Thursday, 30 January 2014 at 17:11:24 UTC, Steven Schveighoffer wrote: On Thu, 30 Jan 2014 11:58:15 -0500, Frustrated c1514...@drdrb.com wrote: Essentially what it boils down to is treating interfaces like classes that have no fields). To avoid the diamond problem simply always choose the method that is not from the interface(since it is default), which is done naturally with the vtable. It's simpler than that. A function is a block of code. A vtable entry points to a block of code. Just point the vtable entry at the block of code that is the default implementation. -Steve Right, this was my original point and why I thought there was already entries for the interface in the vtable(since I seemed to have called some function that did nothing when it should have). It seems so simple and offers some benefit(would at the very least stop requiring one to implement a class every time they want test a design. When programming to interfaces and using some type of factory it makes even more sense. It then could also be used to test is something is implemented(possibly for versioning). e.g., interface A { void hasSomeFeature() { assert(0, Not implemented yet); } } Someone can come along and implement the feature and you(the interface) knows it's implemented if it doesn't assert, set a flag, or whatever. Are you 100% sure no default space is created for the vtable? (trying to reconcile why that case I mentioned worked. I'll try to throw an example up... may have just been coincidence I didn't get a segfault)
Re: How to call opCall as template?
On Thursday, 30 January 2014 at 16:53:33 UTC, Namespace wrote: On Thursday, 30 January 2014 at 16:47:46 UTC, Frustrated wrote: On Thursday, 30 January 2014 at 16:28:42 UTC, Namespace wrote: On Thursday, 30 January 2014 at 16:24:00 UTC, Stanislav Blinov wrote: void main() { F f; int i = f(3,4,5); float f_ = f!float(6, 7, 8); } Does not work, it fails with: Error: template instance f!float f is not a template declaration, it is a variable f.opCall!float(6, 7, 8); ... Yes, of course. But where is the sense to use opCall if I need to call it explicitly? Could you not use opDispatch? Not sure if you can templatize it or not though... Example? I did not know how. doesn't seem to work with templates, I suppose you could try and add it as a feature request? module main; import std.stdio; interface A { void foo(); static final New() { } } class B : A { void foo() { writeln(this is B.foo); } void opDispatch(string s, T)(int i) { writefln(C.opDispatch('%s', %s), s, i); } } void main() { B a = new B; //a.foo(); a.test!int(3); // any *good* reason why this shouldn't work? }
Re: How to call opCall as template?
Also, http://dlang.org/operatoroverloading.html#Dispatch and possible solution to your problem: http://www.digitalmars.com/d/archives/digitalmars/D/opDispatch_and_template_parameters_117095.html Couldn't get code to compile though... but if it did, it should solve your problem.
Re: Interfaces allow member definitions?
On Thursday, 30 January 2014 at 17:11:24 UTC, Steven Schveighoffer wrote: On Thu, 30 Jan 2014 11:58:15 -0500, Frustrated c1514...@drdrb.com wrote: Essentially what it boils down to is treating interfaces like classes that have no fields). To avoid the diamond problem simply always choose the method that is not from the interface(since it is default), which is done naturally with the vtable. It's simpler than that. A function is a block of code. A vtable entry points to a block of code. Just point the vtable entry at the block of code that is the default implementation. -Steve But what if you want to provide some default behavior? We are not dealing with abstract classes here. Since there is currently no way to do what I am saying no solution will be adequate unless it fulfills the behavior. (again, it's not like we can't accomplish basically the same thing, the point is mainly about simplification) The question was about if there was any innate reason why this type of behavior couldn't be accomplish using the vtable. I'm assuming there is none and it could easily be done? (the compiler just has to reserve the space and setup the pointers to the functions?)
Re: How to call opCall as template?
import std.stdio; struct B { template opCall(T) { void opCall(T x) { writeln(x); } } } template a(T) { } void main() { B a; a(3); // works because template parameter can be deduced from arguments a.opCall!(int)(3); // same as about but explicit a!(int)(3); // works but calls template because a! refers to a template // no way to use the above syntax to initiate an opCall on a because it is template notation. // at most one might get away with a.!(int)(3) but this is invalid } You'll never be able to do a!()() for the reasons give above. At most it would have to be implemented the compiler and I doubt it will ever happen. (for example, one could have the opExclamation but then one has ambiguity, which is why ! was chosen to avoid in the first place) I think for your example, the first case works fine using deduction.
Re: Interfaces allow member definitions?
On Thursday, 30 January 2014 at 20:17:23 UTC, Steven Schveighoffer wrote: On Thu, 30 Jan 2014 14:58:42 -0500, Frustrated c1514...@drdrb.com wrote: On Thursday, 30 January 2014 at 17:11:24 UTC, Steven Schveighoffer wrote: On Thu, 30 Jan 2014 11:58:15 -0500, Frustrated c1514...@drdrb.com wrote: Essentially what it boils down to is treating interfaces like classes that have no fields). To avoid the diamond problem simply always choose the method that is not from the interface(since it is default), which is done naturally with the vtable. It's simpler than that. A function is a block of code. A vtable entry points to a block of code. Just point the vtable entry at the block of code that is the default implementation. -Steve But what if you want to provide some default behavior? We are not dealing with abstract classes here. Since there is currently no way to do what I am saying no solution will be adequate unless it fulfills the behavior. (again, it's not like we can't accomplish basically the same thing, the point is mainly about simplification) The question was about if there was any innate reason why this type of behavior couldn't be accomplish using the vtable. I'm assuming there is none and it could easily be done? (the compiler just has to reserve the space and setup the pointers to the functions?) The interface defines the vtable, the class contains a value for that vtable. If you imagine an interface vtable like this: interface A { void foo(); } = struct A_vtbl { void function() foo; } Note the default value is NULL. When you create a class that inherits, it's class info contains an A_vtbl: class B : A { void foo() {writeln(hi;} } = struct B_typeinfo { A_vtbl a_interface = {B.foo}; } And when you call foo on an instance of A, it uses the vtable, knowing that the layout is A_vtbl. (this is simplistic, the real thing is more complex to explain, it's somewhere on the docs). What I'm saying is, if you give a default to the function foo, then our straw-man A_vtbl looks like this: struct A_vtbl { void function() foo = A.default_foo; } And when you create B_typeinfo, if you haven't defined foo, it just points at that default foo (of course, you have to fill in B.foo, and for that, you actually have to do a thunk to convert to the interface I think, but this is not hard). But it's important to note that A does not define an instance of A_vtbl, just the layout! You still need a concrete class to get a vtable instance to point at. -Steve But what I think you are failing to realize is that regardless that foo is defined in an interface, since foo does not use this, it does not depend on the object, so it does not need an object(for all practical purposes it is a static function but of course must take an object as the first parameter so it is compatible as a member function). Also, regardless that it is an interface, doesn't mean it can't have a concrete vtable to work with. The fact is that a vtable is more complex because it has the ability to call functions defined in a base class. In this case a base interface. Just because something doesn't exist there now doesn't mean it can't exist. Answer me this class A { void foo() { } } class B : A { } B b = new B; b.foo(); are you telling me there are actually two foo functions? or does b actually call A's foo passing it the object b e.g., the call made is actually foo(b); If so, then what if A is an interface? (by interface, I am talking about one that has a vtable created for it's members) interface A { void foo() { } } class B : A { } B b = new B; b.foo(); Whats the difference? Absolutely nothing but your interpretation of what an interface is. This is all about semantics. If you want to think of an interface as some idealized abstract compile time object that doesn't exist at run time and has no vtable then so be it. But that doesn't mean it has to be and I'm just saying it is limiting. Obviously the difference between the two above is that the compiler does not allow multiple inheritance w.r.t, to classes, and does not allow fields in interfaces, etc... but these rules can still be enforced on a class THAT HAS A VTABLE. I think you still keep trying to fit the square peg in the round hole. I'm not talking about what the compiler does... we know the above code as I intend it does not work.
Re: Interfaces allow member definitions?
On Thursday, 30 January 2014 at 21:16:05 UTC, Steven Schveighoffer wrote: On Thu, 30 Jan 2014 15:57:06 -0500, Frustrated c1514...@drdrb.com wrote: On Thursday, 30 January 2014 at 20:17:23 UTC, Steven Schveighoffer wrote: But it's important to note that A does not define an instance of A_vtbl, just the layout! You still need a concrete class to get a vtable instance to point at. But what I think you are failing to realize is that regardless that foo is defined in an interface, since foo does not use this, it does not depend on the object, so it does not need an object(for all practical purposes it is a static function but of course must take an object as the first parameter so it is compatible as a member function). But what if it does need an object? interface A { void foo() { bar();} // need 'this' to call bar void bar(); } I've said many times that the functions could not use this. If you are going to go that far then why not allow interfaces to have fields? In this case they would not be any different from classes. Also, regardless that it is an interface, doesn't mean it can't have a concrete vtable to work with. The fact is that a vtable is more complex because it has the ability to call functions defined in a base class. In this case a base interface. Just because something doesn't exist there now doesn't mean it can't exist. Keep in mind that an interface vtable exists as part of an object. The compiler knows this, and performs thunks when necessary. Answer me this class A { void foo() { } } class B : A { } B b = new B; b.foo(); are you telling me there are actually two foo functions? or does b actually call A's foo passing it the object b e.g., the call made is actually foo(b); There is one function, but two vtables, one for A, and one for B. Both point at the same function. Yes, and they could point to the function defined in the interface. When they call it, they would pass themselves as this. The methods in the interface do not use this, so it doesn't matter (they could potentially use it but it would require that it always be valid) If so, then what if A is an interface? (by interface, I am talking about one that has a vtable created for it's members) interface A { void foo() { } } class B : A { } B b = new B; b.foo(); Whats the difference? Absolutely nothing but your interpretation of what an interface is. The difference is, now there is only one vtable, and one interface vtable inside B. A has no vtables. If you do this: A a = new B; a now points at the interface struct *inside B's object*. When you call a.foo, it does this: 1. It looks up in the interface vtable for A that's specific for B (accessed via the interface struct in the object itself) to get the function to call. 2. Included in the interface vtable struct is an offset to add so the 'this' pointer actually points at the object itself instead of the interface struct. Who says A doesn't have a vtable? That's something that you are forcing on it. You have to get off that if we are ever to make any headway. This is all about semantics. If you want to think of an interface as some idealized abstract compile time object that doesn't exist at run time and has no vtable then so be it. But that doesn't mean it has to be and I'm just saying it is limiting. An interface instance and an object instance are two VERY different things, and are handled differently by the compiler. -Steve Again, you have to get off of what has been defined. You have the mentality exactly the same as those that thought the earth was flat, imaginary numbers were nonsense/useless, man couldn't go to the moon. If you define your knowledge on what you already know what is the point? You just run around in circles nothing changes you'll just continue believing the earth is flat...
Re: Interfaces allow member definitions?
Simple question. What are the difference between an interface and a class? I'm not talking about what the compiler does with them. I'm talking about what they were created to do, how they came about etc. If you have to explain to someone what a class is and what an interface is, then you diff that, what is your answer? vtables should not show up in your explanation(they would if I didn't mention it and it shows that you are stuck on the implementation aspect and can't see the forest).
Re: How to call opCall as template?
On Thursday, 30 January 2014 at 21:33:09 UTC, Namespace wrote: I think for your example, the first case works fine using deduction. Sure but this is not always possible. ;) It seems that the problem occurs also with opIndex and so probably with all op* methods. See: http://forum.dlang.org/thread/bug-1204...@https.d.puremagic.com%2Fissues%2F#post-lcegar:241ld2:241:40digitalmars.com Yes, because they all are implicit. It looks like you are calling a template. D could figure this out but I think it will end up having similar issues as has in C++. Is it an a templated op* on an object or is it template function call?
Re: Interfaces allow member definitions?
On Thursday, 30 January 2014 at 21:42:39 UTC, Steven Schveighoffer wrote: On Thu, 30 Jan 2014 16:23:55 -0500, Frustrated c1514...@drdrb.com wrote: Again, you have to get off of what has been defined. You have the mentality exactly the same as those that thought the earth was flat, imaginary numbers were nonsense/useless, man couldn't go to the moon. OK, then. With that, I shall retire from this discussion :) -Steve It would be nice if you could understand what I'm getting at but it's like I keep telling you the earth and you don't believe me ;) Almost surely we are arguing about different things. Mine is more syntax substitution and yours is more implementation. In any case, it doesn't matter because it will never be implemented the way I think it could be so we are just wasting our time(or I'm wasting yours, how ever you want to see it ;)
Static Factory
(Guess is didn't get sent, I guess I'm just a big spam bot cause I keep getting flagged every post) The following code demonstrates a way to have an easy factory in D requiring very little work. I imagine it can be improved to handle the abstract case(basically dependencies/constraints). Any ideas on how to improve it? I think auto serialization of the data of the object will end up being the default behavior. One should be able to templatize the save/restore code. Once this is all done I would think very little work would be required in creating pluggable code(simply use the templates). module main; import std.file, std.stdio; // Mixin iStaticFactory into an interface to provide generic pluggable derived instantiation. // Must use New(id, data) as a way to instantiate a new object of type A(specified by ID) : T. New() is allowed but only provides // default type and is not pluggable. A msg is given anywhere New() is used(should only be used when pluggability is not desired) or during mock up. // // The corresponding mixin template cStaticFactory must be used in all derived types that are to be pluggable. // // The user must provide a way to store and retrieve the object data to allow generic and configurable pluggability. As is, // any derived type of T may be substituted for T dynamically.. mixin template iStaticFactory(T) { @property string _getID(); // returns the type name for this object static final T function(string data)[string] _Creators; // An AA of functions that are registered by the classes which are desired to be plugged into the interface T. // Generic New function that returns an initiated instance of a derived type of T corresponding to data.ID. static final T New(string file = __FILE__, size_t line = __LINE__, string mod = __MODULE__)(string id, string data = null) { if (id != null _Creators[id] != null) return _Creators[id](data); return myA.New(null); // provides default type } // Non-Generic New function returning a default derived type of T used for testing purposes or default object static final T New(string file = __FILE__, size_t line = __LINE__, string mod = __MODULE__)() { pragma(msg, StaticFactory: Not pluggable at ~mod~:~std.string.chomp(line.stringof, u)~ [~file~]); return New(null); } } // Mixin cStaticFactory into any class A derived from interface T to allow it to be pluggable. Mixin static final A New to provide data initialization of object. mixin template cStaticFactor(A, T) if (is(A : T)) { enum _ID = std.traits.fullyQualifiedName!A; @property string _getID() { return _ID; } // Registers this class with the _Creators of T's StaticFactory allowing it to be used to create it's own type. (interface is only used to ensure the class is registered at runtime. Could be done elsewhere or dynamically) static interface iStaticFactory { static this() { T._Creators[_ID] = New; } } // Creates and instantiates this type with data. Override to instantiate data. static final T New(string data) { A t = new A; if (data == null) return t; return t; } } // Demo: interface A { mixin iStaticFactory!A; void foo(); } class myA : A { mixin cStaticFactor!(myA, A); void foo() { writeln(---Called from myA); } } class otherA : A { mixin cStaticFactor!(otherA, A); void foo() { writeln(Called from otherA); } } void main() { enum fn = tempSFdata.tmp; // load/create our object. A a = A.New(exists(fn) ? cast(string)read(fn, 100) : null); // Display object's typeDo something with the object writeln(Current object type is ~a._getID~ with output :); a.foo(); // Provide mechanism to change object foreach(k, v; A._Creators) { if (k == a._getID) continue; writeln(Would you like to change to ~k~ [y/n]); if (readln() == n) continue; // Set a to new object type, assume no data a = v(null); std.file.write(fn, a._getID); writeln(Changed to ~k~); break; } }
automatic type creation
I'd like to support extensions of my own interfaced based design where anyone could simply drop in there own inherited classes and everything would work as if they designed everything using those classes from the get go. To do this though, I need a way to know how to generate these unknown types(except I know the inherit the interface I have designed). e.g., interface A { static final A New() { return new myA; // we have to return something tangible that acts like A. } } class myA : A//never used directly except as a base for actual work, A is used as the reference type in all programming and myA is hidden. { } class anotherA : A // someone elses A, not known at all at compile time. This may be generated by a dll at some future point { } ... In the production code, myA, anotherA, and any other class based on A will never be used, only the interface A. e.g., auto a = A.New(); which obviously returns a myA. I do not want this if the anotherA is now meant to be used, that is, the user of the code wants to redefine the behavior of all the code I write by plugging in their own class implementation instead of using mine. This is all fine and dandy and easy to accomplish by adding a static delegate A which can then be overridden to return anotherA after the fact. The method I'm actually using is to use a template that essentially returns the concrete implementation of any interface I have designed. This then produces identical results as if I just used classes directly but by using interfaces too I can have multiple inheritance. But as far as coding is concerned I just use the interfaces but any time I new an interface it's corresponding class is returned. Of course, the problem with this is that it's an either or approach. Either my implementation is completely used or not. What I'd really like is a way to create objects for the interfaces that at any point could be any one of the implementations of the interface. This way, essentially, the following could be done: auto a = A.New(); // returns myA //somewhere else were an anotherA is meant to be used: auto b = A.New(); // returns anotherA which, of course, as is, won't work unless New somehow knew when it was suppose to use myA's and use anotherA's(Which would be cool if it could because then the user could replace my implementations selectively where ever it wants). The only thing I can think of that might work is to supply a parameter to New that tells it which object to return and allow the user to add their own creation mechanism to the delegate(sort of like allowing them to add to a switch statement dynamically). I'd then have to save/restore dynamically the parameter at every New() call so it is never hard coded(which would allow it to be changed how ever and the change would persist in the program). I will give you an example: Suppose you have an Icon interface that draws icons and allows interaction and all that. You also implement a default type of icon that simply displays the icon image. Now suppose you want to allow others to write their own implementations. Say someone want's to add right mouse button properties to it, the ability to execute the icon, etc. As far as you are concerned within the own logic of your program, it matters not what they do. You want icons to be used in a specific way, say to be visualized on a desktop. If people want to expand on your idea still within some constraint of the interface, you have no problem with that. While you can predict all possible uses and you can write code in a way that might satisfy everyone's implementation ideas, you can at least, allow them to implement the interface on their own and possibly provide them with some generic stuff that most people would need. The main thing is, you have the interface to work with and they supply that at a minimum so their implement will plug and play. BUT!!! What if 10 people implement 10 completely and all cool icon classes and you want some way to allow all 10 to be used in any way desired. If the user wants 1 of each they can have it. In this case you can't use the all or nothing approach. Each implementation still is plug and play but how to allow any to be used when it is suppose to? This necessitates that New is more complex. A sort of factory that has some idea on it's own which type of object it is suppose to return *when*. It would be very similar to the Dependency Injection pattern but because it occurs at creation this is impossible(and static injection of the creation mechanism doesn't seem very safe nor generic). So, in my own code I would have many lines of code that use something like new myIcon;, which forces me to use my own implementation. If I changed it to a sort of static factory I might have Icon.New() which returns whatever specific implementation but for all further created icons until it is changed again. (that is, Icon.New() is a sort of static dependency
Re: automatic type creation
On Sunday, 26 January 2014 at 05:19:51 UTC, Ali Çehreli wrote: Where is the tldr; section? :) On 01/25/2014 04:08 AM, Frustrated wrote: I'd like to support extensions of my own interfaced based design where anyone could simply drop in there own inherited classes and everything would work as if they designed everything using those classes from the get go. I think the concept-based polymorphism popularized by Sean Parent may be relevant. The following is an example where the subtypes Cat and Dog are not inherited from Animal but still behave specially. The design naturally allows hierarchical designs where for example an Animal of Animal(Dog) can be constructed. (See the WAT? line below.) import std.stdio; struct Animal { void sing() { animal.sing(); } this(AnimalT)(AnimalT animal) { this.animal = new Model!AnimalT(animal); } private: interface Interface { void sing(); } class Model(T) : Interface { T t; this(T t) { this.t = t; } void sing() { t.sing(); } } Interface animal; } struct Cat { void sing() { writeln(meow); } } struct Dog { void sing() { writeln(woof); } } void main() { Animal[] animals = [ Animal(Cat()), Animal(Dog()), Animal(Animal(Dog())) /* WAT? :) */ ]; foreach (animal; animals) { animal.sing(); } } Ali While this is interesting I don't think it specifically addresses the issue of having only to create the interface in the original code but have it automatically create the desired type at runtime. In the above code you have to specify cat and dog and are simply wrapping the desired code. If I were using the above code it would be something like Animal[] animals = [Animal.New(State), Animal.New(State), Animal.New(State)]; and somehow New would use the state to know which to create(in this case, cat, dog, and an animal wrapped dog). (of course, the above code would be rather useless and hard to determine the appropriate state information)
TLF = thread local functions
So, TLS solves the data issue with threading. I just thought, with out much thinking, what about having thread local functions? Doesn't make sense? Let me explain. Functions generally are not thread safe because of reentry, right? The same data is used by the function for each thread calling it and sense threads could effectively call a function while the same function is being executed by another thread, the data is correct. To solve this, why not parameterize functions based on threads. Essentially: void funcThread1(...) { ... } void funcThread2(...) { exactly the same code as above } funcThread1 is only ever called on thread 1 and funcThread2 is only ever called on thread 2. There is no issues of threading as these functions are essentially thread local. We can also combine them into one function: // set stack based on threadidx before call. (for n threads there are n stacks for this function) void funcThread(...) { ... } in this case, the compiler can simply set the stack based on the thread id. Should this not solve issues with functions in threading in a similar way that TLS works? (it's just making the stack thread local and functions are just code and data, the data part being the issue) While suck code might not work in all scenarios(such as in general parallelization) it would make code for threading much simpler to write(no locks) in many cases. As far as I can see, the only real issue is that the stack is not thread local for functions and hence acts as a global variable for functions, which is the problem? Is this possible?
Re: TLF = thread local functions
On Thursday, 23 January 2014 at 14:49:11 UTC, Dicebot wrote: On Thursday, 23 January 2014 at 14:44:01 UTC, Frustrated wrote: Functions generally are not thread safe because of reentry, right? No. They are not thread safe because they use shared data (explicitly/implicitly). Functions that only use thread-local data are always thread-safe. Um, duh, but in d data is already TLS. The point is that making the **STACK** TLS too should a way around having to use synchronization. Precisely because the STACK is not TLS makes functions not thread safe(since data is already safe in d). A strongly pure thread local function would never have any threading issues what so ever. Hence, no synchronization would be required and they would be very fast(just an extra instruction or two to fix up the stack if the thread id can be quickly known).
Compare type with another at CT
I am trying to compare a type with another type at compile time. My code is class Q(T) { static auto foo() { static if (T is A) { ... } static assert(0, error); } } and get the error cannot interpret A at compile time on the static if line. A is an interface. I simply want to determine if a type is derived from another type at compile time.
Re: Compare type with another at CT
Yes, I that is what I tried initially but the error was due to that static if. Not sure why but static if (is(T : A)) { ... } static assert(0, error); doesn't work as the assert is called no matter what. Initially I forgot to return the value after changing the code but that doesn't matter. Had to change it to static if (is(T : A)) { ... return ...; } else static assert(0, error); return null; I guess because return is not static in some sense.
Re: Is continuously seeding a random number generator performance intensive?
On Wednesday, 15 January 2014 at 21:00:57 UTC, Jeroen Bollen wrote: How do you correctly create a MersenneTwisterEngine with a ulong as seed? If you are trying to create a very large 2D noise generator, this is how you do it, and you can any degree of smoothness you want: Create a 2D RNG. e.g., RND2D(x,y) { seed(S + x + N*y); return rand; } You could use this to generate your whole map very predictably up to the seed length(at some point it will repeat because of the finite size of the seed). If you have any degree of smoothness you do not want to use this per point unless you do want to have some noise which could be controlled by weighting the RND2D function so intergrid points are not so random: RND2D(x,y, xS, yS) { s = RND2D(x,y) sm1m1 = RND2D((int)(x/xS) - 1, (int)(y / yS - 1)); sm1m1 = RND2D((int)(x/xS) - 1, (int)(y / yS + 1)); ... return interpolate(s, x, y, sm1m1, sm1p1, ...); } where interpolate returns the modified seed that is partially based on the seed at the point x,y and partially an interpolation value between the sub grid points. Anyways, now that you have your RND2D you don't ever have to pre-generate your noise. Obviously it is more computationally expensive though. I guess this was the function you were looking for before if I now understand what you are trying to do?
Properties and std.container.Array
I've tried insert, indexing, ~=, etc but the length always returns 0. e.g., std.container.Array!int arr; arr ~= 3; writeln(arr.length); works fine, but when the array is a property of a class, it does not work, e.g., class x { std.container.Array!int _arr; @property std.container.Array!int arr() { return _arr; } @property std.container.Array!int arr(std.container.Array!int a) {_arr = a; return _arr; } } if I use _arr directly then everything works. Why are properties screwing up std.container.Array?
Re: Properties and std.container.Array
On Thursday, 9 January 2014 at 14:51:33 UTC, monarch_dodra wrote: On Thursday, 9 January 2014 at 13:32:08 UTC, Dicebot wrote: On Thursday, 9 January 2014 at 12:19:25 UTC, Frustrated wrote: I guess I see what is going on. Since Array is a struct, a local copy is made and that never ends up updating the original? How can I use it then like an object so this is not a problem? returning by ref may do what you want: @property std.container.Array!int arr() { return _arr; } - @property ref std.container.Array!int arr() { return _arr; } As dicebot says, however, the issue is a bit more subtle. An `Array` is actually little more than a pointer to a payload. Passing by value is almost free, and updating a copy *should* update the original... ...that is, if it wasn't for the Gotcha that the `Array` needs to be initialized first. But overall, by ref should be just fine. I thought about using ref after the fact. It is a significant rework of my code but it does seem to work. I am not initializing the Arrays. It seems that a better approach maybe to wrap the Array in a class and use alias this? If Array does need to be initialized(seems to work fine without it but maybe a memory leak?) this could be done in the class. What I worry about is end up with a bunch of copies of the array and none of them updated properly. It doesn't seem quite right to have it as a struct.
Re: Properties and std.container.Array
I think maybe using alias this would not solve the problem? One would have to dispatch all the calls on the class to the array. (simply wrap the struct but prevent the compiler from thinking it is a strut so it doesn't use value semantics on it)
singleton with momento
Lets suppose I have setup some code to use a singleton object. Now lets suppose I want to duplicate that code(say to run multiple times simultaneously). The singleton pattern itself prevents multiple copies. One would need multiple instances to be able to run multiple times BUT in the context of each piece of code the object would be a singleton. It seems one would need a singleton would allow in some cases to not be a singleton. While I'm sure there are some ways around this using a singleton directly I wonder if there is any modified pattern to handle this situation? Basically if one thought of having a signal universe with an object in it that is a singleton, then decided to end up with multiple universes. In this case there would be copies of the singleton pattern but with regard to each universe they should behave as expected... and each universe is completely separated from all the others). Anyone know how to easily deal with this? In my code essentially I have a universal context(a singleton) that contains some universal objects(singletons). The context is just a container of all the important data that user code needs quick access too. I know at some point I'll need to have multiple independent contexts to allow for some advanced processing. Hence I can't have them as singletons but I do want some level of uniqueness(No copies floating around in the universe). (instead of having to save, change, then restore the context for every context switch) I'm thinking of something like singleton!(class, universe) where universe is an id but I'm not sure if that is quite right.
Re: Is continuously seeding a random number generator performance intensive?
On Thursday, 2 January 2014 at 20:38:10 UTC, Jeroen Bollen wrote: D provides a set of Random Number Generators in std.random. I am writing an application which would create a 2D map of noise. To do this though, I'll have to calculate the same random numbers over and over again. (I cannot store them, that'd take a horrible amount of RAM. ) Is it good to re-seed a generator for every coordinate, will this be performance intensive? Is there maybe way to easily implement Generator.at(uint x) in D? I believe you fail to understand how the RNG's work. You supply a seed(a value) and they generate a deterministic sequence off that value that is pseudo-random relative to each other.. If you re-seed the generator every time you are not doing anything but wasting cycles since the new element will be random, but the same as using the next element in the sequence in the first case. e.g., seed(k); for(i = 1..10) print(rnd(i)); and for(i = 1..10) { seed(time); print(rnd(i)); } will both produce random sequences of numbers(and random sequences of numbers are identically random. The nice thing about the first case is that you can save the seed once time and produce the exact same sequence... which would save you memory. In the second case you would have to record every seed to recover the sequence.
Re: Easy way to implement interface properties?
On Wednesday, 1 January 2014 at 14:30:46 UTC, Gary Willoughby wrote: On Wednesday, 1 January 2014 at 12:09:40 UTC, Jacob Carlborg wrote: On 2014-01-01 01:52, Frustrated wrote: Is there an easy way to implement properties of an interface within a class instead of having to duplicate almost the exact same code with generic properties? interface A { @property int data(); @property int data(int value); } class B : A { @property int data() { return m_data; } // read property @property int data(int value) { return m_data = value; } // write property } You can't use an abstract class? Yes this is the ideal time to use an abstract base class and is what i would do. The same thing *could* be achieved using mixin templates, with or without scopes but could lead to unmaintainable code. See the examples on mixin templates here: http://nomad.so/2013/07/templates-in-d-explained/ With abstract classes I would still have to implement generic code and it would not be much different than using a standard class(The inheritance is only about 2 levels deep but many interfaces). I don't see how the mixin method would be unmaintainable since it simply implements what hasn't been implemented(it could lead to bugs if one forgets to implement stuff but that's easy to check(functions could throw exceptions in retail build)). Basically Adam's approach is what I was looking for as I see it as the best way unless you have any specific reasons why it doesn't work well. (of course the interface implementer isn't robust but I'm working on that)
Re: Determine if a member is a method
On Wednesday, 1 January 2014 at 15:10:56 UTC, Dicebot wrote: On 2014-01-01 08:43, Frustrated wrote: Also, how does one get the exact code string of a member instead of having to piece it together from info from std.traits? (which requires a lot of work)? Have a look at https://github.com/rejectedsoftware/vibe.d/blob/master/source/vibe/internal/meta/codegen.d#L177 (cloneFunction) for inspiration (it is based on fullyQualifiedName from Phobos) There seems to be a bug. When I run it on a standard member it works fine. When I run it on a property it throws an error src\phobos\std\traits.d(344): Error: forward reference of variable parentPrefix src\phobos\std\traits.d(505): Error: template instance std.traits.fullyQualifiedNameImplForSymbols!(Array!double) error instantiating src\phobos\std\traits.d(295):instantiated from here: fullyQualifiedNameImplForTypes!(Array!double, false, false, false, false) (admittedly it might not suppose be used on properties but it shouldn't crash and burn. Not sure if this is an issue with vibe.d or phobos)
Easy way to implement interface properties?
Is there an easy way to implement properties of an interface within a class instead of having to duplicate almost the exact same code with generic properties? interface A { @property int data(); @property int data(int value); } class B : A { @property int data() { return m_data; } // read property @property int data(int value) { return m_data = value; } // write property } lots of duplicate info, specially when there are a lot of properties, and changing anything in the interface requires changing it in the class. Instead I'd like to do something like class B : A { implement!A; } where implement!A implements all the properties and functions in A that are not already defined in B using simple methods(just returning default values for functions and wrapping a field for properties). This way I can design the structural aspect of the software without having to worry about implementation but still do some basic testing. I can also slowly build up the functionality of the code by implementing properties and functions without having to worry about an all or nothing approach(or having to worry about the original problem of code duplication).
Re: Interface abstraction
On Wednesday, 1 January 2014 at 00:31:58 UTC, Adam D. Ruppe wrote: On Wednesday, 1 January 2014 at 00:31:03 UTC, Frustrated wrote: auto a = new B; // should return cast(A)(new B); A a = new B; case where a being of type B will hurt since it is always implicitly castable to type A. Right, it'll always be usable anyway. I guess I was thinking just for consistency since I'll always being trying to use interfaces instead of classes. I guess it's not a big deal though. In setting up little test units I'll end up using the classes and auto but probably not in the full project where I'll use factories and such.
Re: Easy way to implement interface properties?
On Wednesday, 1 January 2014 at 00:53:53 UTC, Namespace wrote: On Wednesday, 1 January 2014 at 00:48:13 UTC, Frustrated wrote: Is there an easy way to implement properties of an interface within a class instead of having to duplicate almost the exact same code with generic properties? interface A { @property int data() { return m_data; } // read property @property int data(int value) { return m_data = value; } // write property } Without access to some members, yes: make the methods final. With (as in your case): Only with an abstract class or with a mixin template. This was somehow posted before I finished. Final is not the way I want to do it(I'll still have to write code with it, but that's besides the point as it adds extra work that is not necessary). I simply need a way to build up the functionality of the code instead of having to write a bunch of code that will change anyways. One can't use interfaces directly(since they generally contain no code) and one can't build up an interface full of code since that defeats the purpose(just use classes in the first place). I just don't see any reason(and there is none, except to waste time, or for love of typing) to implement default generic behavior over and over when it can *easily* be automated.
Determine if a member is a method
How does one determine if a member is a method and not anything else? Also, how does one get the exact code string of a member instead of having to piece it together from info from std.traits? (which requires a lot of work)?
Re: Easy way to implement interface properties?
On Wednesday, 1 January 2014 at 01:55:19 UTC, Adam D. Ruppe wrote: On Wednesday, 1 January 2014 at 01:33:04 UTC, Frustrated wrote: But your template mixin is still duplicating generic code that should be easily handled automatically. (Generic properties are just wrappers around private fields that always have the same code (just return or set the field)) Oh yeah, that can be done too. Here's an example: http://arsdnet.net/dcode/autoimpl.d The mixin template is implemented by a helper function, which loops over the interface methods and builds a code string for it. It doesn't handle complex cases, like a setter without a getter, but it is a start. The pragma(msg) in there shows you the generated code when it compiles, which can help debugging or just show you what's going on, of course you can remove that when you're happy with it. This doesn't quite work(at least for me) and seems unstable. Doesn't get all the attributes(what if you have a safe property? And doesn't get methods. It is a start though
Bug in imports
I have a rather complex setup of interfaces inheriting from each other in multiple modules. Everything was working fine until I added a new interface and included it at the end of a public imports list: ... about 20 module imports ... public import newModule; newModule contains an interface which I use with other interfaces in other modules. After doing this I end up with a lot of forward reference errors. I put the import at the front and everything worked fine. e.g., public import newModule; ... about 20 module imports ... Luckily newModule does not depend on any previous modules else I imagine I would end up with a circular reference that would be impossible to fix easily. --- module A; import modules; interface iA : iB { ... } interface iAA { ... } -- --- module B; import modules; interface iB : iAA { ... } -- --- module modules; public import A; public import B; /* or public import B; public import A; */ -- I don't have time to try this out but this is what seems to be going on in my program(just renamed and shorted everything).
Re: Idiomatic way to share mutable data?
On Sunday, 22 December 2013 at 21:07:11 UTC, Charles McAnany wrote: Friends, I'm writing a little molecular simulator. Without boring you with the details, here's the gist of it: struct Atom{ double x, vx; double interaction(Atom a2){ return (a2.x-this.x)^^2; //more complicated in reality } } main(){ Atom[] atoms = (a bunch of atoms in random positions); foreach(timestep; 1..1000){ //L0 foreach(atom; atoms){ //L1 foreach(partner; atoms){ //L2 atom.vx += atom.interaction(partner)/mass; //F=ma } } foreach(atom; atoms){ //L3 atom.x += atom.vx * deltaT; } } } So here's the conundrum: How do I parallelize this efficiently? The first loop, L0, is not parallelizable at all, and I think the best speedup will be in parallelizing L1. But I immediately run into trouble: all the threads need access to all of atoms, and every atom's position is changed on every pass through L0. So to do this purely with message passing would involve copying the entirety of atoms to every thread every L0 pass. Clearly, shared state is desirable. But I don't need to be careful about the shared state at all; L1 only reads Atom.x, and only writes Atom.vx. L3 only reads Atom.vx and only writes Atom.x There's no data dependency at all inside L1 and L3. Is there a way to inform the compiler of this without just aggressively casting things to shared and immutable? On that note, how do you pass a reference to a thread (via send) without the compiler yelling at you? Do you cast(immutable Atom[]) on send and cast(Atom[]) on receive? Partition the atoms up into n sets, have a thread per set. A thread only writes to it's set. It can read from other sets. No locks needed and no need to partition the time. If there are many atoms on a large scale, you can try to group them into sets based on distance. Then you can greatly optimize the calculations by ignoring sets that are far away and contribute little to the force(or use an point mass as an approximation. This could reduce the calculations from n^2 to something like n or nlogn.
D references
Is there a site/page with links to really useful reference material for D? It would be nice to have on the dlang site too. I'm specifically looking for the complete phobo's docs in pdf. I came across them some time ago but can't find them now. (good for offline viewing)
Re: D references
(I do believe you can build the docs from the source but I'm not interested in that since it is already done)
Re: Circular Buffer
But does it rely on the GC?
Circular Buffer
I'm in need of a circular buffer/array. I am using std.container.array to avoid the GC. I suppose I could copy and modify the code but is there any easier way? It looks like it is defined as templates so could I somehow hijack the code and modify only what is needed rather than duplicate a lot of stuff? (or maybe someone could just add it to the library... circular arrays are useful ya know ;)
Ranges require GC?
I assume that ranges require the GC, is this true?