views:

105

answers:

3

Say I have to deal ushort and uint some way, but string differently. So guess I need one specialized template for string and other to both ushort and uint. Is it?


// for most
void func(T)(T var) { ... }

// for uint and ushort
void func(T: uint, ushort)(T var) { ... }

That is the idea, although the code can't compile. It's valid or very bad?

+6  A: 

Try this:

void func(T)(T var) if ( is(T : uint) || is(T : ushort) )
{
   ...
}

void func(T : string)(T var)
{
   ...
}

You could also do it in one function:

void func(T)(T var)
{
    static if ( is(T : uint) || is(T : ushort) )
    {
        ...
    }
    else if ( is(T : string) )
    {
        ...
    }
    else
    {
        // handle anything else
    }
}
Peter Alexander
Note that in the first example he is using Template Constraints, and the second is a compile time conditional, 'static if.' The first should be used if there are types the template does not handle, the second can be used with the first or when everything is handled.
he_the_great
+5  A: 

If you need only specific types, follow Peter's answer.
If you would like to cover all integral/numeric data and all string (including wstring and dstring) data types, then you could use helpers from std.traits module:

import std.traits;

void func(T)(T var)
{
    static if (isNumeric!T) { //  or isIntegral!T
        //...
    } else if (isSomeString!T) {
        //...
    }
    else {
        //...
    }
}
van
Useful trick, +1! However specific types was the problem.
Pedro Lacerda
Yes, very useful, and these template helpers can also be used in Template Constraints.
he_the_great
A: 

You are not precise understand his meaning mix multi template parameters should do like this void func(T...)(T args) { static if(T.length==2&&is(T[0]:int)&&is(T[1]:short)) { //do some thing func(int,short) }else static if(T.length==1&&is(isSomeString!T[0]) { }otherwise { static assert("unsupport function"); }

}

galaxylang