Different class template args to generate same template instance?
    Nick Sabalausky 
    a at a.a
       
    Mon Nov  2 14:12:55 PST 2009
    
    
  
"downs" <default_357-line at yahoo.de> wrote in message 
news:hcnjit$4na$1 at digitalmars.com...
> Nick Sabalausky wrote:
>> "BCS" <none at anon.com> wrote in message
>> news:a6268ffc3898cc29d1f554dfe2 at news.digitalmars.com...
>>> Hello Nick,
>>>
>>>
>>>> So...is there any trickery I
>>>> could do so that SubFoo!("sam") and SubFoo!("sam", "human") would
>>>> resolve to the same subclass of Foo?
>>> Make a SubFoo!(char[] s) that does your logic and if it passesa alises 
>>> to
>>> SubFoo!(s,"")
>>>
>>>
>>
>> I'm not sure I understand...?
>>
>>
>
> I think what he's trying to say is
>
> template SubFoo!(char[] name, char[] type) {
>  static if (name == "sam" && (type == "human" || type == "")) alias 
> _SubFoo!("sam", "human") SubFoo;
>  /* etc */
> }
Ahh! Thanks all, that works perfectly:
-------------------------------------------------------------
module foo;
class Foo
{
    protected char[] _n="Plain Foo";
    char[] n()
    {
        return _n.dup;
    }
}
template SubFoo(char[] name, char[] type="")
{
    static if (name == "sam" && (type == "human" || type == ""))
        alias _SubFoo!(name, "human") SubFoo;
    else static if(
        (name == "zoe" && type == "human") ||
        (name == "zoe" && type == "starship")
    )
        alias _SubFoo!(name, type) SubFoo;
    else static if(name == "zoe" && type == "")
        static assert(false, "Name '"~name~"' is ambiguous");
    else
        static assert(false, "Invalid name/type: '"~name~"' '"~type~"'");
}
private class _SubFoo(char[] name, char[] type) : Foo
{
    static if(name == "sam" && type == "human")
        this() { _n = "sam human"; }
    else static if(name == "zoe" && type == "human")
        this() { _n = "zoe human"; }
    else static if(name == "zoe" && type == "starship")
        this() { _n = "zoe starship"; }
    else
        static assert(false, "Invalid name/type: '"~name~"' '"~type~"'");
}
-------------------------------------------------------------
module main;
import tango.io.Stdout;
import foo;
void main()
{
    auto f  = new Foo();
    auto s_ = new SubFoo!("sam");
    auto sh = new SubFoo!("sam", "human");
    auto zh = new SubFoo!("zoe", "human");
    auto zs = new SubFoo!("zoe", "starship");
    // ERROR: Name 'zoe' is ambiguous
    //auto z_ = new SubFoo!("zoe");
    // ERROR: Invalid name/type 'dummy' 'dude'
    //auto d_ = new SubFoo!("dummy", "dude");
    Stdout.formatln("f : {}", f.n);  // OUT: f : Plain Foo
    Stdout.formatln("s_: {}", s_.n); // OUT: s_: sam human
    Stdout.formatln("sh: {}", sh.n); // OUT: sh: sam human
    Stdout.formatln("zh: {}", zh.n); // OUT: zh: zoe human
    Stdout.formatln("zs: {}", zs.n); // OUT: zs: zoe starship
}
-------------------------------------------------------------
    
    
More information about the Digitalmars-d-learn
mailing list