【发布时间】:2016-01-21 13:47:08
【问题描述】:
以下代码已使用 gcc 5.3.0 成功编译,但无法使用 clang 3.7.0 编译。在这两种情况下,我都使用了具有相同命令行选项的在线 coliru 编译器:-std=c++14 -O2 -Wall -pedantic -pthread。
#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;
}
clang 拒绝它并出现以下错误:
error: constexpr variable 'res_foo' must be initialized by a constant expression
constexpr size_t res_foo = foo(arg);
~~~~^~~~
由于两个编译器之间的这种差异,我想知道这是否是一段有效的代码。如果没有,我想更好地理解为什么会这样。
【问题讨论】:
-
gcc 错误,是 constexpr 的众多错误之一
-
@TemplateRex 但是
foo以什么方式破坏了 constexpr 函数的任何规则? -
@Archimaredes 不是,错误是
test中的arg不是constexpr