以下代码段已成功使用gcc 5.3.0进行编译,但未能使用clang 3.7.0进行编译。在这两种情况下,我使用了在线coliru编译器和相同的命令行选项:-std = C++ 14 -O2 -Wall -pedantic -pthread。参数仅用于constexpr函数体内的未评估的上下文中
#include <cstdio>
// Definition of constexpr function 'foo'.
constexpr std::size_t foo(const int& arg_foo) { return sizeof(arg_foo); }
// Definition of function 'test'.
void test(const int& arg)
{
// The following line produces an error with clang.
constexpr std::size_t res_foo = foo(arg);
// Print the result returned by the 'foo' function.
std::printf("res_foo = %lu\n", res_foo);
}
// Definition of function 'main'.
int main(int argc, const char* argv[])
{
// Test function call.
test(argc);
// Return statement.
return 0;
}
铛与以下错误拒绝它:
error: constexpr variable 'res_foo' must be initialized by a constant expression
constexpr size_t res_foo = foo(arg);
~~~~^~~~
由于两个编译器之间的这种差异,我想知道如果这是一个代码有效片。如果没有,我想更好地理解为什么会出现这种情况。
海湾合作委员会的错误,很多时,它涉及到constexpr – TemplateRex
@TemplateRex但是'foo'破坏constexpr函数的任何规则? – Archimaredes
@Archimaredes没有,错误是''测试''arg'不是'constexpr' – TemplateRex