constexpr函数中的GCC constexpr lambda和编译时评估 [英] GCC constexpr lambdas in constexpr functions and evaluation in compile time

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

问题描述

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

和以下代码示例进行测试/验证(即,它评估

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函数

call to non-constexpr function ''

现在做点小事研究我发现尚不支持 constexpr lambda。

Now doing a litle research I discovered that constexpr lambdas aren't support yet.

为什么不支持 constexpr lambda,我们可以在其中定义 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),代码确实格式错误;尽管相应的提案正在分发中。 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.

这篇关于constexpr函数中的GCC constexpr lambda和编译时评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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