以下代码在 Intel-2015 上编译正常,但在 gcc 4.8.3 上编译失败 谁是对的?
#include <iostream>
void f( int const& x ) { std::cout << x << std::endl; }
struct S
{
static constexpr int ce = 42;
};
int main()
{
f(S::ce);
return 0;
}
g++ 错误:
/tmp/ccOIxa2V.o: In function `main':
test_constexpr.cpp:(.text+0x36): undefined reference to `S::ce'
collect2: error: ld returned 1 exit status
最佳答案
因为函数 f
接受一个引用参数,所以必须有一个 S::ce
的定义,一个引用可以在运行时指向;编译器不能只用文字 42 替换参数。所以你必须添加一个类外定义:
const int S::ce;
就像您使用非constexpr
变量一样。这会在运行时为值分配一个内存位置,供引用和其他无法在编译时计算的内容使用。
参见 this GCC bug report (其中有解释为什么它实际上不是错误的评论)以获取更多信息。
关于c++ - Intel vs GCC on constexpr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28324686/