Different class template args to generate same template instance?

Nick Sabalausky a at a.a
Mon Nov 2 12:21:16 PST 2009


I'd like to have a sub-class that's templated on a potentially-duplicated 
name and an optional disambiguating type. To illustrate:

class Foo
{
}

/*
Three possible names/types are:
- sam, human
- zoe, human
- zoe, starship
*/
class SubFoo(char[] name, char[] type)
{
    static if(name == "sam" && type == "human")
        // create members specific to the only sam
    else static if(name == "zoe" && type == "human")
        // create members specific to the human zoe
    static if(name == "zoe" && type == "starship")
        // create members specific to the starship zoe
    else
        static assert(false, "Invalid name/type");
}

But unlike in that example, *most* of the names will only exist as one 
possible type and will therefore be completely unambiguous just by 
themselves. So, I would really like to be able to make the type optional and 
just have a "static assert(false)" for any use of an ambiguous name that 
isn't disambiguated by a type. Kind of like this:

class SubFoo(char[] name, char[] type="")
{
    static if(name == "sam" && (type == "human" || type==""))
        // create members specific to the only sam
    else static if(name == "zoe" && type == "human")
        // create members specific to the human zoe
    static if(name == "zoe" && type == "starship")
        // create members specific to the starship zoe
    static if(name == "zoe" && type == "")
        static assert(false, "zoe might be either the human or the starship, 
please specify which one");
    else
        static assert(false, "Invalid name/type");
}

Problem is, that won't work because SubFoo!("sam") and SubFoo!("sam", 
"human") are treated as different types. So...is there any trickery I could 
do so that SubFoo!("sam") and SubFoo!("sam", "human") would resolve to the 
same subclass of Foo?

I don't think any solution involving merging the name/type fields into 
anything like "sam.human" would work because the valid names could be just 
about any sequence of chars (this source file will be generated by a tool) 
so any possible "disambiguated" string could potentially conflict with a 
plain non-disambiguated name. Names being any sequence of chars also rules 
out anything like "class SubFoo_sam_human : Foo", because name could be 
something like "++.  /&".




More information about the Digitalmars-d-learn mailing list