【问题标题】:C++ templates specialization syntaxC++ 模板特化语法
【发布时间】:2012-01-09 13:06:51
【问题描述】:

在 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

谷歌搜索了一下,我只找到了 No.3 的例子。它们之间有什么区别(在调用、编译、使用方面)?其中一些是否已过时/已弃用?为什么不直接使用 No.1?

【问题讨论】:

  • 这要么是一个糟糕的翻译,要么就是你弄错了。我建议你阅读更多关于模板和函数重载的区别。
  • 通常使用(并考虑)术语“函数模板”是一个好主意,因为它强调它是一个模板,而不是一个函数,并且无论何时需要函数,您都可以'不使用模板(只是一个特化,因为那时那些是函数)。

标签: c++ template-specialization


【解决方案1】:

以下是每种语法的 cmets:

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

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

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

并了解术语:

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

看到这个:

【讨论】:

  • +1,注意重载可能是首选。
  • @avakar:附有 Herb Sutter 的相关 GotW Why Not Specialize Function Templates? 文章的链接
  • 显式实例化应为template void foo&lt;int&gt;(int param),或推导模板参数时为template void foo&lt;&gt;(int param)
  • @fefe:是的。正确的。忽略了这一点。无论如何编辑我的答案。谢谢。
  • 您的倒数第二个不正确。这是一个有效的显式特化。不需要
【解决方案2】:

使用 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-05
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    相关资源
    最近更新 更多