function template specialization question D vs. C++

Nicholas Wilson iamthewilsonator at hotmail.com
Sun Jan 14 00:30:37 UTC 2018


On Sunday, 14 January 2018 at 00:09:42 UTC, kdevel wrote:
> fusp.d
> ```
> import std.stdio;
> import std.typecons;
>
> void foo (T) ()
> {
>    writeln ("(1) foo T = ", T.stringof);
> }
>
> void foo (T : float) ()
> {
>    writeln ("(2) foo T = ", T.stringof);
> }
>
> // void foo (T : double) ()
> // {
> //    writeln ("(2) foo T = ", T.stringof);
> // }
>
> void main ()
> {
>    foo!float;
>    foo!double;
>    foo!real;
>    foo!string;
> }
> ```
>
> prints
>
>    (2) foo T = float
>    (2) foo T = double
>    (2) foo T = real
>    (1) foo T = string
>
> I would have expected
>
>    (2) foo T = float
>    (1) foo T = double
>    (1) foo T = real
>    (1) foo T = string
>
> The compiler does not allow me to specialize the primary 
> function template for double:

The `:` is not a type equality check. It is more like a "converts 
to" or "is of the form of".
i.e. `void foo (T : float) ()` reads as "foo is a template 
function returning void, taking one template type T that converts 
to float, and no runtime args."

The usual way to do what you are trying to do is with template 
constraints.

void foo(T)() if (is(T== float)) { ...}


More information about the Digitalmars-d-learn mailing list