【发布时间】:2018-05-21 15:45:06
【问题描述】:
以下代码被 GCC 7.2 和 clang 5.0.0 接受,但被 Microsoft VS 2017 15.5.0 Preview 5 和 Intel C++ compiler 19 拒绝:
struct S { };
constexpr int f(S)
{
return 0;
}
int main()
{
auto lambda = [](auto x)
{
constexpr int e = f(x);
};
lambda(S{});
}
微软:
<source>(12): error C2131: expression did not evaluate to a constant
英特尔:
<source>(12): error: expression must have a constant value
constexpr int e = f(x);
^
<source>(12): note: the value of parameter "x" (declared at line 10) cannot be used as a constant
constexpr int e = f(x);
^
如果我用f(decltype(x){}) 替换f(x),微软和英特尔都不会抱怨。我了解x 不是常量表达式,但在f 内部没有使用。这可能是 GCC 和 clang 不抱怨的原因。
我猜微软和英特尔的编译器拒绝这个代码是正确的。你怎么看?
【问题讨论】:
-
@RichardHodges,
-std=c++14. -
好的,现在我认为这是 gcc 和 clang 的一个错误,因为 c++14 不附带 constexpr lambda ......这从 c++17 开始可用
-
@W.F.,lambda 故意不是
constexpr(在实际代码中不是)。 -
MSVC 还抱怨:“失败是由读取超出其生命周期的变量引起的” 并且 g++ 和 clang 抱怨未使用的变量。如果您从 lambda 中 return,它们会编译。
-
@Bob__
f(x)应该用在需要常量表达式的上下文中。当您执行return f(x)时,您不会在编译时强制评估f(x)。
标签: c++ lambda c++14 language-lawyer