【问题标题】:Template explicit instantiation (definition and declaration) in gcc [duplicate]gcc中的模板显式实例化(定义和声明)
【发布时间】:2014-02-25 13:59:07
【问题描述】:

假设有这样的代码:

template <typename T>
CLASS_KEY1 X{};

PREFIX template CLASS_KEY2 X<int>;

其中CLASS_KEY1CLASS_KEY2PREFIX 是宏。 CLASS_KEY1CLASS_KEY2 可以扩展为 classstructunion 关键字。 PREFIX 可以扩展为空字符集或 extern 关键字。

下表显示了何时为所有宏值组合(编译器 gcc-4.8.1,选项 -std=c++11)编译此类代码(Yes - 编译,No - 不编译):

PREFIX                                        extern  extern  extern
CLASS_KEY1\CLASS_KEY2 class   struct  union   class   struct  union
class                 Yes     Yes?    No      Yes     Yes?    No
struct                Yes?    Yes     No      Yes?    Yes     No
union                 No      No      Yes     No      No      Yes

这是 gcc 中的错误还是标准要求中的错误(奇怪的情况用问号标记)?其他编译器呢?

【问题讨论】:

  • 从封装策略来看,structclass没有区别。我敢打赌,保留政策是在定义类的地方宣布的。
  • 但是,当您尝试这样做时,clang++ 会产生警告:warning: class template 'X' was previously declared as a struct template。两个编译器都应用在定义类的地方宣布的封装策略。
  • @Morwenn 感谢您的解释和参考。

标签: c++ templates gcc c++11 explicit-instantiation


【解决方案1】:

C++11 标准的第 7.1.6.3 节(详细类型说明符)说:

elaborated-type-specifier 中的 class-keyenum 关键字应与 中的名称所对应的声明实物一致详细类型说明符 是指。该规则也适用于声明 class-namefriend 类的 elaborated-type-specifier 形式,因为它可以解释为引用班级。因此,在任何详细类型说明符中,enum 关键字应用于引用枚举 (7.2),unionclass-key 应为用于引用 union(第 9 条),classstruct class-key 应用于引用使用声明的 class(第 9 条) classstruct class-key.

所以,你看到的行为是允许的。

【讨论】:

  • 感谢您的报价。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-23
  • 2018-07-05
  • 2012-09-29
  • 1970-01-01
相关资源
最近更新 更多