Function overloading is more flexible than template function specialization -- Raymond Chen

RaymondChen_5in-150x150.jpgWhen trying to specialize a templated function for specific types, it’s easy to fall into subtle traps around how parameter types are matched. A colleague recently ran into this issue while attempting to specialize a function for a Widget and a string literal, only to be met with confusing compiler errors that hinted at deeper quirks in C++'s type deduction and function template specialization rules.

Function overloading is more flexible (and more convenient) than template function specialization

by Raymond Chen

From the article:

A colleague of mine was having trouble specializing a templated function. Here’s a simplified version.

template<typename T, typename U>
bool same_name(T const& t, U const& u)
{
    return t.name() == u.name();
}

They wanted to provide a specialization for the case that the parameters are a Widget and a string literal.

template<>
bool same_name<Widget, const char[]>(Widget const& widget, const char name[])
{
    return strcmp(widget.descriptor().name().c_str(), name) == 0;
}

However, this failed to compile:

// msvc
error C2912: explicit specialization 'bool 
same_name<Widget,const char[]>(const Widget &,const char 
[])' is not a specialization of a function template

What do you mean “not a specialization of a function template”? I mean doesn’t it look like a specialization of a function template? It sure follows the correct syntax for a function template specialization.

Add a Comment

Comments are closed.

Comments (0)

There are currently no comments on this entry.