【问题标题】:Why is the following template declaration ill-formed? [duplicate]为什么以下模板声明格式不正确? [复制]
【发布时间】:2015-04-03 09:57:54
【问题描述】:

为什么下面的声明无效?

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++ templates c++11 standards


    【解决方案1】:

    基本上,“因为标准是这样说的。” C++11 14.1/1 列出了 type-parameter:

    的语法

    类型参数:
    class...opt标识符opt
    class 标识符opt= type-id
    typename...opt标识符opt
    typename 标识符opt= type-id
    template &lt; 模板参数列表 &gt; class ...opt标识符 选择
    template &lt; 模板参数列表 &gt; class 标识符opt= id 表达式

    如您所见,模板模板参数只允许使用class。

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

    这已经随着 C++11 的别名模板而改变,但模板模板参数语法显然没有跟上。然而,在 C++11 后(实际上是 C++14 后)draft N4296 中,这个限制实际上被解除了,template &lt;class&gt; typename 是有效的模板模板参数语法。

    【讨论】:

    • 在 N4296 中,它的指定方式有所不同。在 open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf 的 14.1/1 中,它似乎有所不同。这是否意味着这个限制将会改变?
    • @MathiasVorreiterPedersen 显然是这样。
    • “唯一的类型模板是类模板。”别名模板
    • @Columbo 刚刚解决了它
    • 虽然从技术上讲它是“后 C++11”草案,但 n4296 也是后 C++14。这是 C++1z 的最新版本
    猜你喜欢
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 2019-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多