c++ - 为什么以下模板声明格式错误?

标签 c++ templates c++11 standards

<分区>

为什么下面的声明无效?

template<template<typename> typename T>
struct S {};

我认为这是有效的,因为以下是有效的:

template<template<typename> class T>
struct S {};

我可以从 [gram.temp] 中的标准中读取它似乎是有效的,但是 gcc 给了我以下输出:

prog.cpp:4:38: error: expected 'class' before 'T'
 template<template<typename> typename T>
                                  ^

最佳答案

基本上,“因为标准是这么说的。” C++11 14.1/1 列出了类型参数的语法:

type-parameter:
  class ...opt identifieropt
  class identifieropt = type-id
  typename ...opt identifieropt
  typename identifieropt = type-id
  template < template-parameter-list > class ...opt identifieropt
  template < template-parameter-list > class identifieropt = id-expression

如你所见,只有class允许用于模板模板参数。

我的基本原理猜测是任何类型都可以用作类型参数,包括非类类型。但在 C++11 之前,没有“非类类型模板”这样的东西——唯一的类型模板是类模板。

C++11 的别名模板改变了这一点,但模板模板参数语法显然没有跟上。尽管如此,在后 C++11(实际上是后 C++14)中 draft N4296 , 这个限制实际上被取消了 template <class> typename是有效的模板模板参数语法。

关于c++ - 为什么以下模板声明格式错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29429961/

相关文章:

c++ - 右值引用和文字

c++ - 正确答案但在效率阶段出现运行时错误

c++ - FBX SDK 骨骼动画

c++ - std::vector 如何访问它们之间有巨大差距的元素?

ruby-on-rails - 在 Rails 模板中读取文件

angularjs - 从文件加载 $templateCache

c++ - 将 Boost ublas 矩阵写入文本文件

c++ - OpenGL 纹理颜色问题

c++ - 不完整类型 Qt 的无效使用

c++ - 在 C++ 中模板化一个 'for' 循环?