1

When you declare a template specialization, what's the difference between the syntax with (1) and without angular brackets (2).

Why the version 1 fails if an implementation (definition) of the method is not provided (like in this case) with the error: undefined reference to int f<int>(int) while the version 2 works as expected?

template <typename T> T f(T val) {
    return val;
}
template<> int f<int>(int val); // 1
template int f<int>(int val);   // 2
int main() {
    cout << f(555);
}

I've seen this answer but it does not explicitly descrive the difference between these different syntax.

Community
  • 1
  • 1
barsdeveloper
  • 930
  • 8
  • 28
  • 3
    #1 is specialization, #2 is explicit instantiation. – interjay Sep 11 '15 at 15:54
  • 1
    The [answer](http://stackoverflow.com/a/8323597/1417883) you linked explains these forms as being specialization and instantiation. Furthermore, it also links to another [answer](http://stackoverflow.com/questions/3914642/difference-between-instantiation-and-specialization-in-c-templates) that explains their difference. – James Adkison Sep 11 '15 at 15:59
  • You're right. The comment "same as above" was confusing for me. – barsdeveloper Sep 11 '15 at 16:01

2 Answers2

3

You just confused explicit instantiation and template specialization.

No1 is template spcialization, means you want to define a special version for the template with the given type, so you have to provide a potentially different defination for it.

No2 is explicit instantiation, means you want the compiler to instantiate the template with the given type explicitly. It will be generated based on the primary template.

Explicit instantiation:

An explicit instantiation definition forces instantiation of the function or member function they refer to. It may appear in the program anywhere after the template definition, and for a given argument-list, is only allowed to appear once in the program.

An explicit instantiation declaration (an extern template) prevents implicit instantiations: the code that would otherwise cause an implicit instantiation has to use the explicit instantiation definition provided somewhere else in the program.

explicit (full) template specialization:

Allows customizing the template code for a given set of template arguments.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
0

In the first case, you're telling the compiler to specialize the template function (saying "the template for type int is different"), but you're not providing the specialized function definition, hence the "undefined reference". This error pretty much always means: "You declared a function, used it elsewhere, and did not define it".

maxbc
  • 949
  • 1
  • 8
  • 18