【问题标题】:Syntax for explicit template specializations显式模板特化的语法
【发布时间】:2015-09-25 18:41:13
【问题描述】:

gcc-4.9.2 和 clang-3.8 在编译为 C++98 或 C++11 时都接受以下内容,

#include <cstdio>

template <typename T> void f(T) { printf("T\n"); }
template <> void f<int>(int) { printf("int\n"); }    // explicit specialization
template <> void f<>(double) { printf("double\n"); } // explicit specialization -- 14.7.2(7)
template <> void f(float) { printf("float\n"); }     // HERE

int main() {
  f(1L);    // T
  f(10);    // int
  f(10.0);  // double
  f(10.0F); // float
}

我看到在 C++11 标准 §14.7.2(7) 中允许在显式模板特化中推导尾随模板参数,但我找不到标记为 HERE 的简洁形式是否被允许或如何被允许。

这些编译器是一致的还是某些扩展?

【问题讨论】:

  • 这些都不是显式实例化。它们是明确的专业化
  • @T.C. ups & 谢谢,现在修好了。
  • 我没有标准中的确切引用,但我记得如果可以推断出类型,您至少可以在函数调用中省略尖括号。专业领域可能也允许这样做。
  • 其实,我只是在 wandbox 上用 gcc3.6.3 和 c++03 运行这个例子,它也被接受了:melpon.org/wandbox/permlink/…

标签: c++ language-lawyer


【解决方案1】:

C++14 标准 §14.7(3) 有

可以为函数模板、类模板、类模板的成员或成员模板声明显式特化。 template 引入了显式的特化声明。在类模板、类模板的成员或类成员模板的显式特化声明中,显式特化的类的名称应为 simple-template-id。在函数模板或成员函数模板的显式特化声明中,显式特化的函数或成员函数的名称可以是模板ID。

然后演示

template<class U> void g(U) { }
template<> void g(char) { }       //specialize for U == char
                                  // U is deduced from the parameter type

然后我们有§14.7.3(10)

如果可以从函数参数类型推导出来,则可以在命名显式函数模板特化的模板 ID 中未指定尾随模板参数。 [ 例子:

template<class T> class Array { / ... / };
template<class T> void sort(Array<T>& v);

// explicit specialization for sort(Array<int>&)
// with deduced template-argument of type int
template<> void sort(Array<int>&);

——结束示例]

【讨论】:

  • 这很有趣,C++14 的 §14.7.3(10) 似乎是从 C++11 的 §14.7.3(8) 发展而来的(好吧,N3376 的)我指的是,只是那里的例子是template void sort&lt;&gt;(Array&lt;int&gt;&amp;);
  • @BenjaminBannier 你确定吗? this N3376 的副本具有相同的 14.7.3(10)。
  • 即使是 2005 年的 n1905 也有。
  • 现在可以,但我把事情搞混了。 §14.7.2(7) 中有一个类似的例子(那是 2,而不是 3),但我确实看到了你引用的 §14.7.3(10)。我认为这也为 C++11 提供了答案,谢谢!
  • 我现在看到 §14.7.3 指的是专业化,而 §14.7.2 谈论的是实例化。我认为这是我查找此内容时感到困惑的一部分。
猜你喜欢
  • 2011-01-07
  • 1970-01-01
  • 1970-01-01
  • 2012-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-04
相关资源
最近更新 更多