method generation by name

Kirk McDonald kirklin.mcdonald at gmail.com
Mon Jul 23 17:23:48 PDT 2007


BCS wrote:
> What is the best way to generate a method with a given name (as 
> specified by a const char[]) without having to build the whole thing as 
> a string?
> 
> I was hoping this would work:
> 
> |template foo(R, char[] name, A...)
> |{
> |  R mixin(name)(A a)
> |  {
> |    return d(a);
> |  }
> |}
> |
> |mixin foo!(int, "hello", int);
> |
> |void main()
> |{
> |  int i = hello(1);
> |}
> 
> the best I have come up with is a bit hackish and has a few "issues".
> 
> |template foo(R, char[] name, A...)
> |{
> |  R somthing(A a){return R.init;}
> |  mixin("alias somthing "~name~";");
> |}
> 
> If a clean solution for this were made and class level static foreach 
> were to be implemented then auto implementation of an interface would be 
> doable.
> 
> 

Building the whole thing as a string is probably the cleanest solution:

template make_func(char[] name) {
     mixin("void "~name~"() {}");
}

mixin make_func!("foo");

void main() {
     foo();
}

You can get rid of some of the ugliness of this approach by factoring 
out the function's implementation into another function, and calling the 
actual implementation inside the string.

void actual_impl() {}

template make_func(char[] name) {
     mixin("void "~name~"() {
         actual_impl();
     }");
}

mixin make_func!("foo");

void main() {
     foo();
}

Whether the function call overhead is worse than stuffing it all inside 
the string is of course up to you.

It is my strident hope that macros -- whenever we get them -- will make 
this particular trick obsolete.

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org


More information about the Digitalmars-d-learn mailing list