Pergunta

My book mentions two ways for explicit specialization:

template <> void Swap<int> (int &, int &);
template <> void Swap(int &, int&);

what is the difference between both? when to use one and when to use the other? what is exactly the <> after the function name?

Foi útil?

Solução

what is the difference between both?

There is no difference.

In the second case, you are letting the compiler perform type deduction from the signature of the specialization. Therefore, both forms declare a specialization of Swap<T>() for T = int.

when to use one and when to use the other?

At your discretion, when one form or the other meets your requirements in terms of readability or ease of maintenance.

what is exactly the <> after the function name?

When it comes after the function name, it is the syntax for specifying template arguments:

template<typename T = double, typename U = char>
void foo();

foo<int, bool>(); // Specifies explicit template arguments
foo<>(); // Use default template arguments
foo(); // Same as above, allowed for *function* templates only

When it comes after the template keyword, it is the syntax for introducing a (class or function) template specialization.

Outras dicas

The first example is the real way to explicitly specialize a template, the second example is just a shortcut for the first way since the compiler can deduced the type itself from the function signature. The result is the same, there is no real difference.

The <>is used to give the template parameter to a templated structure, in this case the template parameter is the type of the manipulated data and the specialization is for the type int.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top