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?
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.
There are two types of templates in C++, function templates and class templates.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With