Explicit C ++ Function Template Specification

My book mentions two ways for explicit specialization:

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

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

+4
source share
2 answers

what's the difference between them?

There is no difference .

In the second case, you allow the compiler to perform type inference from the specialization signature. Therefore, both forms declare Swap<T>() specialization 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 <> after the function name?

When this happens after the function name, this is the syntax for specifying the 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 this happens after the template keyword, this is the syntax for introducing the specialization of the template (class or function).

+3
source

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

<> used to specify the template parameter in the template structure, in this case the template parameter is a type of managed data, and specialization is an int type.

+1
source

All Articles