Template specialization using traits?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Mon Dec 21 03:07:16 PST 2015

On Monday, December 21, 2015 15:14:20 Shriramana Sharma via Digitalmars-d-learn wrote:
> Hello. I want to define a template specialization using traits:
> import std.stdio, std.traits;
> void func(T)(T t) { writeln(1); }
> void func(T)(T t) if(isIntegral!T) { writeln(2); }
> void main()
> {
>     func(1);
> }
> But I'm getting an error saying that the called function matches both. If it
> were a single type, I know I have to put the specialization as in:
> void func(T: int)(T t) { writeln(2); }
> and that works, but how to make it more generic than that?

In D, each template constraint must match exactly once. A template with no
template constraint is the same as having a template constraint that's
always true. So, you need to alter your template constraints so that for a
given template argument, exactly one template constraint is true. There
really isn't such a thing as a specialization when dealing with template
constraints. Using : like in your second example is the only kind of
template specialization that we have.

For your example to work with template constraints, the most straightforward
solution would be

void func(T)(T t)

void func(T)(T t)

- Jonathan M Davis

More information about the Digitalmars-d-learn mailing list