Template specialization

Ali Çehreli via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Thu Jan 21 16:08:56 PST 2016


On 01/21/2016 03:37 PM, Darrell Gallion wrote:
> How do you create a template that accepts many types.
> But overrides just one of them?
> Don't want to write out all of the specializations.
>
> Hours of google and I'm sure it's simple...
>
> -=Darrell

The straightforward approach is tricky because the ': int' syntax means 
"is implicitly convertible"; so, even the case where B is 'char' would 
be bound to the specialization:

void foo(A, B, C)() {
     pragma(msg, "general");
}

void foo(A, B : int, C)() {  // <-- 'B : int' specialization
     pragma(msg, "special");
}

void main() {
     foo!(char, string, double)();
     foo!(short, int, float)();
}

A better approach is using template constraints:

void foo(A, B, C)()
         if (!is (B == int)) {  // <-- 'B != int'
     pragma(msg, "general");
}

void foo(A, B, C)()
         if (is (B == int)) { // <-- 'B == int'
     pragma(msg, "special");
}

void main() {
     foo!(char, string, double)();
     foo!(short, int, float)();
}

But that has its own problem of needing to reverse the logic for the 
general case (and other cases), which may become very complicated to 
write (or to get right) in some cases.

Ali



More information about the Digitalmars-d-learn mailing list