C++模板专业化语法

Jan*_*roň 49 c++ template-specialization

在C++ Primer Plus(2001,捷克语翻译)中,我发现了这些不同的模板特化语法:

功能模板

template <typename T> void foo(T);
Run Code Online (Sandbox Code Playgroud)

专业化语法

void foo(int param); // 1
void foo<int>(int param); // 2
template <> void foo<int>(int param); // 3
template <> void foo(int param); // 4
template void foo(int param); // 5
Run Code Online (Sandbox Code Playgroud)

谷歌搜索了一下,我发现只有3号例子.它们之间是否存在差异(通话,编译,使用)?其中一些是否已过时/弃用?为什么不使用No.1?

Naw*_*waz 75

以下是每种语法的注释:

void foo(int param); //not a specialization, it is an overload

void foo<int>(int param); //ill-formed

//this form always works
template <> void foo<int>(int param); //explicit specialization

//same as above, but works only if template argument deduction is possible!
template <> void foo(int param); //explicit specialization

//same as above, but works only if template argument deduction is possible!
template void foo(int param); //explicit instantiation
Run Code Online (Sandbox Code Playgroud)

我添加:

//Notice <int>. This form always works!
template void foo<int>(int param); //explicit instantiation

//Notice <>. works only if template argument deduction is possible!
template void foo<>(int param); //explicit instantiation
Run Code Online (Sandbox Code Playgroud)

从编码的角度来看,重载优于功能模板专用.

所以,不要专门化功能模板:

并了解术语:

  • 实例
  • 显式实例化
  • 专业化
  • 明确的专业化

看到这个:

  • +1,注意可能首选过载. (4认同)
  • 很好的框架答案:) (4认同)