Template constraint and specializations

Philippe Sigaud philippe.sigaud at gmail.com
Fri Mar 23 10:51:46 PDT 2012


On Fri, Mar 23, 2012 at 10:17, Ed McCardell <edmccard at hotmail.com> wrote:

>>> Is there a way to write a template constraint that matches any
>>>
>>> specialization of a given type?
>>
>>
>> Nope. But there are simple workarounds:
>>
>> class Foo(bool feature1, bool feature2) { enum _isFoo = true; }
>>
>> template isFoo(T) {
>>     enum bool isFoo = __traits(hasMember, T, "_isFoo");
>> }

Another solution that does not require you to add an _isFoo member:
use template function instantiation:

template isFoo(T)
{
    enum bool isFoo = __traits(compiles, {

void testFoo(Args...)(Foo!Args arg);

testFoo(T.init);
                                                                });
}

testFoo is a function that accepts any Foo!( ... ) for any ... The
second line tests it on a value of type T (T.init).

This can be generalized even further, to create any template-testing function:

template isA(alias Foo)
{
    template isA(T)
    {
        enum bool isA = __traits(compiles, { void
tester(Args...)(Foo!Args args); tester(T.init);});
    }
}


usage:

alias isA!Foo isFoo;

template useFoo(T) if (isFoo!T)
{
....
}


More information about the Digitalmars-d-learn mailing list