Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple types in one specialized D template

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?

like image 523
Pedro Lacerda Avatar asked Oct 07 '10 05:10

Pedro Lacerda


People also ask

Can you have templates with two or more generic arguments?

Function Templates with Multiple ParametersYou can also use multiple parameters in your function template. The above syntax will accept any number of arguments of different types. Above, we used two generic types such as A and B in the template function.

What are the two types of templates?

There are two types of templates in C++, function templates and class templates.

Can you partially specialize a C++ function template?

You can choose to specialize only some of the parameters of a class template. This is known as partial specialization. Note that function templates cannot be partially specialized; use overloading to achieve the same effect.


1 Answers

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
    }
}
like image 118
Peter Alexander Avatar answered Sep 20 '22 04:09

Peter Alexander