静态constexpr在类中初始化:为什么这些示例表现不同?

时间:2017-09-21 13:10:44

标签: c++ constexpr

我尝试编译以下代码,但失败了。

#include <iostream>
#include <vector>

struct Foo {
  static constexpr int A = 10;
  static constexpr int B = 10;

  std::vector<int> dat;

  Foo() : dat(A, B) {}
};

int main() {
  Foo foo;
}

错误讯息:

$ g++ a.cpp -std=c++11
/tmp/ccSaJJrd.o: In function `Foo::Foo()':
a.cpp:(.text._ZN3FooC2Ev[_ZN3FooC5Ev]+0x25): undefined reference to `Foo::B'
collect2: error: ld returned 1 exit status

奇怪的是,可以编译以下代码:

#include <iostream>
#include <vector>

struct Foo {
  static constexpr int A = 10;

  std::vector<int> dat;

  Foo() : dat(A, 10) {}
};

int main() {
  Foo foo;
}

为什么第二个参数不能获得constexpr值?

0 个答案:

没有答案