模板模板参数,为什么类是强制的?

Ske*_*een 3 c++ templates

如果我写的话,标题几乎说明了一切;

                                        vvvvv
template <template <typename, typename> class StdContainer, typename T>
class DerivedContainer: public StdContainer<T, std::allocator<T>>
{ /*...*/ };
Run Code Online (Sandbox Code Playgroud)

为什么需要 class 关键字?那是当 typename 被允许时,作为所有其他模板上下文中的替代品。消歧?标准的哪一部分也说明了这一点?

笔记; 我不是从标准容器派生的,这只是一个例子。

jro*_*rok 5

class声明模板模板参数时关键字的使用由语法规定:

n3337, §14.1 [temp.param]:

1 模板参数的语法是:

template-parameter:

type-parameter
parameter-declaration

type-parameter:

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

我不知道这样做的确切原因。当您有一个简单的类型参数时,该类型可以是从基本类型到用户声明的类、类模板的特化等的任何内容。当它是模板模板参数时,它只能是类模板的名称。也许他们想强调这种差异 - 或者他们只是不想在语法中插入更多行并增加混乱。谁知道 :)

  • 没有引用,但我认为 C++ 的设计与演进提到所有模板参数曾经*只有*`class` 关键字,当然后来有`typename` 替代来强调也非-类类型可以是模板参数。但是,模板模板参数必须是类,因此没有添加 `typename` 关键字。 (2认同)