www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - How to call binary functions on primitive on runtime?

reply Tom <no.email gmail.com> writes:
how can I make an implementation of some thing like Foo:
 assert(Foo("+", 1, 2) == 1+2);
 assert(Foo("*", 3, 2) == 3*2);


 switch (oper) {
   case "+": return a+b;
   ..
 }


thanks.
Feb 12 2011
parent Jonathan M Davis <jmdavisProg gmx.com> writes:
On Saturday 12 February 2011 10:49:15 Tom wrote:
 how can I make an implementation of some thing like Foo:
 assert(Foo("+", 1, 2) == 1+2);
 assert(Foo("*", 3, 2) == 3*2);


without writing a long switch with case for each operator like:
 switch (oper) {
 
   case "+": return a+b;
   ..
 
 }


I know how to implementation a compile-time equivalent with the mixin statement. thanks.

D really doesn't do stuff like that at runtime. It's fantastic at creating code for you at compile time. But you just don't create functions at runtime in D. Things don't work that way. So, if you want to create a templated function that uses mixins and/or static if, you can do that quite easily. But if you want to somehow construct functions at runtime, you're out of luck. The closest that you'll get is opDispatch, and that still does doesn't do what you're looking for. By it's very nature, it would have to use a case statement or something similar. Really, in D, to do the sort of thing you're trying to do, you do it at compile time with templates and string mixins. - Jonathan M Davis
Feb 12 2011