Multiple Template Specialization Types (in D1)?

Jarrett Billingsley kb3ctd2 at yahoo.com
Wed Jul 2 08:49:13 PDT 2008


"Nick Sabalausky" <a at a.a> wrote in message 
news:g4g69h$j7v$1 at digitalmars.com...
>
> I can't decide if this is better of worse. Leaning towards worse ;)
>
> char[] Bar(char[] retType, char[] publicName, char[] privateName,
>                char[] argsDecl, char[] argsCall, char[][] types)
> {
>    char[] ret;
>    foreach(char[] type; types)
>    {
>        ret ~= "public "~retType~" "~publicName~"(T:"~type~")("~argsDecl~") 
> {"~privateName~"!(T)("~argsCall~");}";
>    }
>    return ret;
> }
>
> mixin(Bar("void", "Foo", "Foo_dwc", "T arg", "arg", ["char", "wchar", 
> "dchar"]));
>
> void main(char[][] args)
> {
>    Foo('a');
> }

Now it's just getting silly.

template MakeFunctions(RetType, char[] PublicName,
    char[] PrivateName, Types...)
{
    static if(Types.length == 0)
        const char[] MakeFunctions = "";
    else
        const char[] MakeFunctions =
    "public " ~ RetType.stringof ~ " " ~ PublicName ~ "(T : " ~
        Types[0].stringof ~ ")(T arg)\n"
    "{\n"
    "   return " ~ PrivateName ~ "(arg);\n"
    "}\n"
    ~ MakeFunctions!(RetType, PublicName, PrivateName, Types[1 .. $]);
}

public template NameOfFunc(alias f)
{
    // weirdness in dmdfe.
    const char[] NameOfFunc = (&f).stringof[2 .. $];
}

private template BarImpl(char[] PublicName, alias PrivateFunc, Types...)
{
    alias typeof(&PrivateFunc!(Types[0])) FuncType;
    alias ReturnTypeOf!(FuncType) RetType;

    const ret = MakeFunctions!(RetType, PublicName,
        NameOfFunc!(PrivateFunc!(Types[0])), Types);
}

public template Bar(char[] PublicName, alias PrivateFunc, Types...)
{
    static assert(Types.length > 0, "must have at least one type");
    const Bar = BarImpl!(PublicName, PrivateFunc, Types).ret;
}

mixin(Bar!("Foo", Foo_dwc, char, wchar, dchar));

Template-foo to the rescue, you can extract the return type directly from 
the alias to the private function.  :)




More information about the Digitalmars-d-learn mailing list