C++ 模板完全特化语法

标签 c++ templates syntax template-specialization

<分区>

声明模板特化时,带 (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.

关于C++ 模板完全特化语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32527334/

相关文章:

java - 我如何从 JSP 调用 C++ 函数

c++ - 链接到 gcc 中的 boost 正则表达式

wpf - 在 WPF 中向 slider 控件添加第二个拇指

javascript - 在 for 循环中使用多个变量的 CoffeeScript 语法

c++ - 从 C++ 函数返回整个自定义类型数组

c++ - C2664 错误 C++ Visual Studio

php - 使用Twig显示PHP对象参数

c++ - 将左值传递给 RValue 的参数

syntax - F# 构造函数语法 - 覆盖和扩充 new

syntax - 多行字符串作为序列的一部分