GCC constexpr lambas在constexpr函数中的求值和编译时间 [英] GCC constexpr lambas in constexpr functions and evaluation in compile time

查看:322
本文介绍了GCC constexpr lambas在constexpr函数中的求值和编译时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码,我们有以下代码用于在编译时累加 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;

LIVE DEMO

现在如果更改运算符 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函数' p>

call to non-constexpr function ''

现在进行小规模的研究我发现 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函数中的求值和编译时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆