opDispatch and compile time parameters

Meta via Digitalmars-d digitalmars-d at puremagic.com
Sat Oct 17 10:13:40 PDT 2015


On Saturday, 17 October 2015 at 15:31:00 UTC, Nikolay wrote:
> I asked on SO question about opDispatch and compile time 
> parameters: 
> http://stackoverflow.com/questions/32998781/opdispatch-and-compile-time-parameters
>
> Currently it looks like it is not possible to use opDispatch 
> for non trivial template functions. I think opDispatch should 
> get function name plus evaluated compile time arguments as 
> first compile time parameter. E.g not just function name "b", 
> but "b.p2!(int, 10)"  See example from SO question:
>
> import std.stdio;
>
> class B{
>     auto p1(T)(T arg) {
>         writeln( "p1: ", arg );
>     }
>     auto p2(T, int C)(T s) {
>         writeln( "p2: ", s, " / ", C);
>     }
> }
>
> class C(T) {
>     T b = new T;
>
>     auto opDispatch(string s, Args...)(Args args) {
>        mixin("b."~s)(args);
>     }
> }
>
> void main() {
>     auto b = new C!(B)();
>     //fine: compiler is smart enough
>     b.p1("abc");
>     //oops: "no property 'p2' for type ..."
>     b.p2!(int, 10)(5);
>     auto origB = new B;
>     //fine:
>     origB.p2!(int, 10)(5);
> }
>
> Is it good idea for opDispatch improvement or may there is some 
> other approach?

There is another approach, which is to automatically generate a 
declaration that more or less matches the one in b. Then you can 
call b.p2 or whatever else on the outer class, and it will be 
forwarded to the inner class. The implementation is a lot hairier 
than you might think, but I've got it mostly working now. I've 
been meaning to post an answer to your StackOverflow question, 
but I wanted to be sure that the implementation was complete and 
as bug-free as possible. You can find the code here: 
https://github.com/MetaLang/phobos/commit/6c5fa291a957f4050910064d1fa44a86ff92e760

Basically, you just do `mixin(forwardToMember!(b, "p1", "p2"));` 
inside your wrapper class and it will automatically declare the 
correct methods/properties/aliases for you. Let me know if it 
works for your usecase and I'll post it to StackOverflow as well.


More information about the Digitalmars-d mailing list