【问题标题】:Initialize a template struct at definition在定义处初始化模板结构
【发布时间】:2013-11-12 22:24:55
【问题描述】:

我不确定这个主题是否完全符合我的要求,但基本上是这样的:

我可以这样做:

struct something {
    int d;
} somethingType;

但是为什么我不能这样做呢?

template <bool T>
struct somethingelse {
    int d;
}<true> somethingelseType;

如果可以做第二个,正确的做法是什么?

【问题讨论】:

  • 你为什么要这样做?
  • 为什么要拍摄土星照片?
  • @AlanStokes 我这样做是因为我不想在 main 中声明它。但是我尝试了第一个,当它起作用时,我决定尝试第二个,这就是我遇到编译器问题的地方

标签: c++ templates struct template-specialization


【解决方案1】:

从语法上讲,我认为你可以,但受到额外限制的禁止:

[温度]/1

模板定义了一个类或函数族或类型族的别名。

   模板声明:
template &lt; 模板参数列表 &gt; 声明

   模板参数列表:
模板参数
模板参数列表 , 模板参数

[...]

模板声明中的声明

  • 声明或定义函数或类,或
  • 定义类模板或嵌套在类模板中的类的成员函数、成员类、成员枚举或静态数据成员,或
  • 定义类或类模板的成员模板,或
  • 是一个别名声明

声明(顶级语法结构)可以是模板声明,因此这些规则直接适用于声明。

另一方面(即对于非模板类),声明也可以是块声明 [dcl.dcl]/1,可以是一个simple-declaration,它可以包含一个decl-specifier-seq,它可以包含一个type-specifier [dcl.type]/1,它可以是一个 class-specifier,它可以声明一个类 o.O,使用这个 type-specifier 你可以声明一个变量:

(将每行的一个构造解析为其(可能的)组件)

声明 块声明 简单声明 decl-specifier-seqopt init-declarator-listopt ; type-secifier init-declarator-listopt ; class-specifier init-declarator-listopt ; class-head { member-specificationopt } init-declarator-listopt ; class-head { member-specificationopt } init-declarator ; class-head { member-specificationopt } declarator initializeropt ; class-head { member-specificationopt } ptr-declarator ; class-head { member-specificationopt } noptr-declarator ; class-head { member-specificationopt } declarator-id attribute-specifier-seqopt; class-head { member-specificationopt } ...opt id-expression ;

现在匹配,例如,struct something { int d; } somethingType;

但这将是一个变量的声明,这对于模板情况是不允许的。

【讨论】:

    【解决方案2】:

    我不认为你可以。

    您可以通过对象名称(根据http://www.cplusplus.com/doc/tutorial/structures/)而不是模板参数来跟踪结构。

    【讨论】:

    • 我并不是说这个答案是错误的(我不确定),但 cplusplus.com 通常不是可靠的来源。使用 cppreference.com,或者更好的 C++ 标准。
    【解决方案3】:

    一个type-specifier可以

    • trailing-type-specifier
    • class-specifier
    • enum-specifier

    如您所见,template-declaration 不包括在内,因此您要查找的内容不存在(直接)

    查看在线版C++11语法规则超链接:http://www.nongnu.org/hcb/#type-specifier

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      • 2013-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多