声明模板特化时,带 (1) 和不带尖括号 (2) 的语法有什么区别。
如果未提供方法的实现(定义)(如本例),为什么版本 1 会失败并出现错误:undefined reference to int f<int>(int)
而版本 2 按预期工作?
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);
}
我看过 this answer但它没有明确描述这些不同语法之间的区别。
您只是混淆了显式实例化和模板特化。
No1 是template spcialization,意味着你想为给定类型的模板定义一个特殊版本,所以你必须为它提供一个可能不同的定义。
No2 是显式实例化,意味着您希望编译器显式实例化具有给定类型的模板。它将基于主模板生成。
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.