opDispatch和编译时间参数

sib*_*ick 6 d

如何使用opDispatch转发到具有编译时参数的方法.见下面的代码:

import std.stdio;

struct B{
    auto p1(T)(T arg) {
        writeln( "p1: ", arg );
    }
    auto p2(T, int C)(T s) {
        writeln( "p2: ", s, " / ", C);
    }
}

struct C(T) {
    T b;

    auto opDispatch(string s, Args...)(Args args) {
        mixin("b."~s)(args);
    }
}

void main() {
     C!B b;
     //fine: compiler is smart enough
    b.p1("abc");
    //oops: "no property 'p2' for type ..."
    b.p2!(int, 10)(5);
    B origB;
    //fine:
    origB.p2!(int, 10)(5);
 }
Run Code Online (Sandbox Code Playgroud)

编辑

用struct替换class:避免使用CTFE进行字段初始化new.这与我的问题无关.

小智 7

D模板系统非常强大.这是更通用的解决方案:

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;
    template opDispatch(string s) {
        template opDispatch(TARGS...) {
            auto opDispatch(ARGS...)(ARGS args) {
                static if(TARGS.length) return mixin("b." ~ s ~ "!TARGS(args)");
                else return mixin("b." ~ s ~ "(args)");
            }
        }
    }
}

void main() {
    auto b = new C!(B)();
    b.p1("abc");
    b.p2!(int, 10)(5);
}
Run Code Online (Sandbox Code Playgroud)

http://dpaste.dzfl.pl/791c65d0e4ee