问题描述
代码,我们有以下代码用于在编译时累加 constexpr std :: array
:
Code first, we have the following piece of code that is used to accumulate a constexpr std::array
in compile time:
template <typename T, std::size_t N, typename O>
constexpr T compile_time_accumulator(const std::array<T, N> const &A, const std::size_t i, const O& op, const T initialValue)
{
return (i < N)
? op(A[i], compile_time_accumulator(A, i + 1, op, initialValue))
: initialValue;
}
和以下代码示例来测试/ varify它(即,在编译时):
and the following code example to test/varify it (i.e., that it evaluates in compile time):
constexpr std::array<int, 4> v {{4, 5, 6, 7}};
std::cout << std::integral_constant<int, compile_time_accumulator(v, 42, std::plus<int>())>::value
<< std::endl;
现在如果更改运算符 std :: plus< int>
与一个 constexpr
lambda:
Now if change the operator std::plus<int>
with a constexpr
lambda:
constexpr auto lambda_plus = [] (int x, int y) { return x + y; };
并按如下调用:
constexpr std::array<int, 4> v {{4, 5, 6, 7}};
std::cout << std::integral_constant<int, compile_time_accumulator(v, 42, lambda_plus)>::value << std::endl;
^^^^^^^^^^^
我收到一个错误lambda不是 constexpr
:
I get an error, that lambda is not constexpr
:
现在进行小规模的我发现 constexpr
lambdas目前还不支持。
Now doing a litle research I discovered that constexpr
lambdas aren't support yet.
为什么不支持 constexpr
lambdas,我们允许定义一个 constexpr
lambda第一个?
Why if constexpr
lambdas aren't supported, we are allowed to define a constexpr
lambda in the first place?
编辑:
似乎clang不接受。那么哪个编译器是正确的?
It seems that clang doesn't accep the code. So which compiler is right?
推荐答案
代码确实是[expr.const] /(2.6)。 lambdas不允许在常量表达式中使用,但正在分发。 GCC在接受 lambda_plus
的声明时不正确。
The code is indeed ill-formed as per [expr.const]/(2.6); lambdas aren't yet allowed in constant expressions, though a corresponding proposal is in circulation. GCC is incorrect in accepting lambda_plus
's declaration.
这篇关于GCC constexpr lambas在constexpr函数中的求值和编译时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!