考虑下面的代码(available on gcc.godbolt.org):使用在非`constexpr`上下文`constexpr`功能的λ:铛VS GCC
template <typename TF>
constexpr auto fn_x(TF f)
{
return f();
}
constexpr auto get_x()
{
return fn_x([]{ return 0; });
}
int main()
{
auto res = get_x();
}
它编译下克++ 5.3.x和更新的(包括g ++ 6.xx)。
它不会下铛++ 3.7.x并用以下错误较新的编译:
error: constexpr function never produces a constant expression [-Winvalid-constexpr]
constexpr auto get_x()
^
note: subexpression not valid in a constant expression
return fn_x([]{ return 0; });
的可能解决方案,以使代码编译GCC和铛使用“间接层”与decltype
,也摆脱在定义lambda的函数constexpr
:gcc.godbolt.org link。
根据标准哪个编译器在这里是正确的?
无论如何,也许与你的问题更相关:做任何你测试的编译器声明'get_x()'可以用在一个常量表达式中?如果不是,你的问题是“我允许将'constexpr'添加到永远不能用于常量表达式的函数吗?” – hvd
@hvd:关于分号,我总是用'-Wpedantic'编译真实的代码,这会告诉我这个错误。我习惯于编写lambda-heavy代码('auto l = [] {...};'),所以有时我的大脑会在函数结尾自动添加分号。 –
@hvd它是有效的C++ 11 - ';'是一个*空声明*。参见[CWG 569](http://wg21.link/cwg569)。 –