模板模板类型名?
当使用 template template 语法时 template <template <typename> class T>
, 需要使用关键字 class
, 作为使用 typename
给出如下错误:
error: template template parameter requires 'class' after the parameter list
其他地方的关键词typename
和 class
在声明模板参数的基本情况下可以互换。
你可能会争辩说,使用模板模板时的要求是暗示你应该传递一个类类型,但情况并非总是如此(尤其是在 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/