C++ 模板完全专业化语法

C++ template full specialization syntax

声明模板特化时,带 (1) 和不带 angular 括号 (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 is 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.

在第一种情况下,您告诉编译器专门化模板函数(比如 "the template for type int is different"),但您没有提供专门化的函数 definition ,因此 "undefined reference"。这个错误几乎总是意味着:"You declared a function, used it elsewhere, and did not define it".