Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ template specialization parameter duplication

Recently I have noticed the following problem with template specializations.

Note if we have the following specialization for f and the template parameter name can be a very long type, possibly derived from other templates.

template <class T> void f(T t) {}

template <>
void f<VeryLongType>(VeryLongType t)
{
    using T = VeryLongType;
    // ...
}

Note this very long type name is duplicated 3 times. Also if f returns a value of this type, then another duplication will be introduced (auto will be a workaround).

I am wondering if there exists some simplified syntax for this so that no duplications are necessary?

Maybe like the following:

template <>
void f<T = VeryLongType>(T t)
{
   // ...
}
like image 641
Lin Avatar asked May 18 '18 19:05

Lin


1 Answers

You don't really need to explicitly specify the specialization type, e.g.:

template <>
void f(VeryLongType t)
{
    using T = VeryLongType;
    // ...
}

is fine. The type alias can be shortened with decltype(t) if VeryLongType is really very long...

using T = decltype(t); // makes it more generic too
like image 106
DeiDei Avatar answered Oct 14 '22 13:10

DeiDei