Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Syntax for specializing function templates in C++

Suppose I have a function template where the type parameter is used as a return type only:

template <typename T>
T foo()
{
    return whatever;
}

Then what is the correct syntax to specialize that function template? Both of the following seem to work:

template <>
std::string foo()
{
    return whatever;
}

template <>
std::string foo<std::string>()
{
    return whatever;
}

Is there any difference between the two? If not, what is the idiomatic way?

like image 612
fredoverflow Avatar asked Aug 05 '11 13:08

fredoverflow


2 Answers

The compiler will deduce the correct template specialization based on informations provided (here, the function return type).

So these syntaxes have exactly the same behaviour, one being more explicit than the other.

like image 130
Maël Nison Avatar answered Sep 22 '22 12:09

Maël Nison


In most case, there is no difference between the two.

If you overload several template functions, the second form may be needed to remove an ambiguity about which overload you mean to specialize (you probably have other problems if you are in this situation, for instance you'll also need to be explicit at call places).

like image 22
AProgrammer Avatar answered Sep 21 '22 12:09

AProgrammer