c++模板专门化语法

C++ templates specialization syntax

本文关键字:语法 专门化 c++      更新时间:2023-10-16

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

函数模板

template <typename T> void foo(T);

专业化语法

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
在谷歌上搜索了一下,我只找到了第三个例子。它们之间(在调用、编译、用法)有什么区别吗?它们中的一些已经过时了吗?为什么不直接用一号呢?

每种语法的注释如下:

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

由我添加:

//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

从编码的角度来看,重载优于函数模板专门化。

所以,不要专门化函数模板:

  • 为什么不特化函数模板?
  • 模板专门化和重载

要了解术语:

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

参见:

    c++模板中实例化和专门化的区别

使用Visual Studio 2012,如果没有函数参数,它的工作似乎略有不同:

template <typename T> T bar( );
//template int bar<int>( ) { return 0; } doesn't work
template < > int bar<int>( ) { return 0; } //does work