"template<>" vs "template" without brackets - what's the difference?

C++TemplatesTemplate Specialization

C++ Problem Overview


Suppose I've declared:

template <typename T> void foo(T& t);

Now, what is the difference between

template <> void foo<int>(int& t);

and

template void foo<int>(int& t);

semantically? And do template-with-no-brackets and template-with-empty-brackets have other semantics in other contexts?


Related to: https://stackoverflow.com/q/2152002/1593077

C++ Solutions


Solution 1 - C++

template <> void foo<int>(int& t); declares a specialization of the template, with potentially different body.

template void foo<int>(int& t); causes an explicit instantiation of the template, but doesn't introduce a specialization. It just forces the instantiation of the template for a specific type.

Solution 2 - C++

With class/struct,

template <typename T> struct foo {};

Following is a specialization:

template <> struct foo<int>{};

Following is an explicit instantiation:

template struct foo<int>;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioneinpoklumView Question on Stackoverflow
Solution 1 - C++Mark BView Answer on Stackoverflow
Solution 2 - C++Jarod42View Answer on Stackoverflow