GCC constexpr lambdas在constexpr函数和编译时的评估

时间:2015-10-15 21:56:58

标签: c++ c++11 lambda c++14 constexpr

代码首先,我们有以下代码用于在编译时累积2015-10-15 14:12:11.434 x ValueA in case -----> Correct / Selected value 2015-10-15 14:12:11.435 x ValueA in set -----> (null) 2015-10-15 14:12:11.435 x ValueB in set -----> (null) 2015-10-15 14:12:11.436 x ValueC in set -----> (null) 2015-10-15 14:12:12.217 x ValueB in case-----> Correct / Selected value 2015-10-15 14:12:12.217 x ValueA in set -----> (null) 2015-10-15 14:12:12.218 x ValueB in set -----> (null) 2015-10-15 14:12:12.218 x ValueC in set -----> (null) 2015-10-15 14:12:14.516 x ValueC in case-----> Correct / Selected value 2015-10-15 14:12:14.517 x ValueA in set -----> (null) 2015-10-15 14:12:14.517 x ValueB in set -----> (null) 2015-10-15 14:12:14.518 x ValueC in set -----> (null)

<tr>
  <td align="left">
    <table>
      <tr>
        <td valign="center" align="left" style="padding: 2px 2px 0 0;">
          <span style="padding: 2px 4px; border: 1px solid #dddddd; border-radius: 6px; -webkit-border-radius: 6px;">
            hashtag
          </span>
        </td>                             
      </tr>
    </table>
  </td>
</tr>

以及以下代码示例来测试/变换它(即它在编译时评估):

constexpr std::array

LIVE DEMO

现在,如果使用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; } lambda更改运算符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不是constexpr auto lambda_plus = [] (int x, int y) { return x + y; };

  

调用非constexpr函数''

现在做了research我发现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; ^^^^^^^^^^^ lambdas还不支持。

问:

为什么不支持constexpr lambdas,我们可以首先定义constexpr lambda?

编辑:

似乎clang不接受code。那么哪个编译器是对的?

2 个答案:

答案 0 :(得分:3)

C ++ 11允许定义constexpr的数量非常有限,而C ++ 14的长列表不是constexpr

  

来自n4296(C ++ 14的候选版本)5.20.2.6

     

5.20常量表达式[expr.const]

     

2条件表达式e是核心常量表达式,除非   评估e,遵循抽象机的规则(1.9),   将评估以下表达式之一:

     

2.6) - 一个lambda表达式(5.1.2);

所以答案是lambda不正常,所以编译器必定是错误的。

答案 1 :(得分:3)

根据[expr.const] /(2.6),代码确实是不正确的;虽然corresponding proposal正在流传,但lambdas还没有被允许用于常量表达式。 GCC在接受Build声明时不正确。

相关问题