简体   繁体   English

GCC 和 clang 之间的 constexpr 差异

[英]constexpr differences between GCC and clang

The following compiles in GCC 9 but not in clang 10 and I'm wondering which of the two compilers is standard conforming:以下在 GCC 9 中编译,但不在 clang 10 中编译,我想知道这两个编译器中哪一个符合标准:

template<typename T>
struct A {
  static const T s;
  static const T v;
};

template<typename T>
constexpr const T A<T>::s = T(1);

template<typename T>
constexpr const T A<T>::v = A<T>::s;

int main(int, char**) {
  constexpr auto a = A<double>::v;
  return 0;
}

This is intended to be a minimal example of a bigger issue which is why the fields s and v are explicitly declared as const but are defined as constexpr , this is intentional.这是一个更大问题的最小示例,这就是为什么字段sv被显式声明为const但被定义为constexpr ,这是故意的。

Is GCC correct to compile that code or is clang correct to reject it? GCC 是正确编译该代码还是 clang 正确拒绝它?

Compilers are only required to treat static const variables of integral and enum types as constexpr if they are initialize with a constant expression.仅需要编译器将整数和枚举类型的static const变量视为constexpr ,前提是它们使用常量表达式进行初始化。 This made it possible to use them as array lengths before constexpr was added to the language.这使得在将constexpr添加到语言之前,可以将它们用作数组长度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM