c++ - 为什么模板模板参数不允许 'typename'在参数列表之后

标签 c++ templates c++11 language-lawyer typename

模板模板类型名?

当使用 template template 语法时 template <template <typename> class T> , 需要使用关键字 class , 作为使用 typename给出如下错误:

error: template template parameter requires 'class' after the parameter list

其他地方的关键词typenameclass 在声明模板参数的基本情况下可以互换。

你可能会争辩说,使用模板模板时的要求是暗示你应该传递一个类类型,但情况并非总是如此(尤其是在 C++11 引入模板化之后)类型别名)。

template <template <typename> class T> // 'class' keyword required.
struct Foo {
    using type = T<int>;
};

template <typename T>
using type = T (*)();

using func_ptr_t = Foo<type>::type;

这背后的原因是什么?

  • 关于为什么 typename 有什么具体原因吗?模板声明中不允许吗?
  • C++ 标准对此有任何说明吗?

最佳答案

简答:因为 Standard says so .

更长的答案:在标准化之前,C++ 模板要求所有模板参数都有 class 关键字。然而,为了强调模板也可以是非类(即内置)类型这一事实,引入了一个替代关键字 typename。然而,在 C++98 中,template-template 参数只能是类类型,这就是那个上下文中没有添加 typename 关键字的原因。

进入 C++11 及其新功能 template aliases ,现在还引入了非类模板,因此引入了非类模板模板参数:

template<typename T> struct A {};
template<typename T> using B = int;

template<template<typename> class X> struct C;
C<A> ca; // ok
C<B> cb; // ok, not a class template
template<template<typename> typename X> struct D; // error, cannot use typename here

以上示例取自当前的 C++1z 提案 N4051标题为 Allow typename in a template template parameter,并建议准确地允许。

Clang 3.5 SVN now supports this使用 -std=c++1z 标志。

关于c++ - 为什么模板模板参数不允许 'typename'在参数列表之后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23965105/

相关文章:

c++ - Qt 自定义小部件不显示子小部件

templates - 内省(introspection)模板参数(尤其是模板别名参数)

c++ - 使用类模板需要模板参数

c++ - 如何推断 C++11 中的模板参数类型?

C++11 别名模板作为特化中的模板模板参数?

c++ - C++串联;字符串+双;运算符+与运算符+ =

c++ - 一次从一 block 内存创建多个 Eigen::VectorXd

c++ - 错误: expected class-name before '{' token { ^

c++ - 为什么需要命名构造函数的 using 声明?

c++ - 我可以使用 foo<T..., int, U...> 这样的模式部分特化模板吗?