【问题标题】:lambda capture error with gcc, compiles with clang使用 gcc 捕获 lambda 错误,使用 clang 编译
【发布时间】:2021-07-24 18:50:16
【问题描述】:

以下程序不能用 g++ 10.1.0 编译

#include <iostream>

template <unsigned int N>
struct A {
  constexpr static unsigned int i = N;
};

template <class U>
void f()
{
  constexpr unsigned int i = U::i;
  auto lambda = [&]() {
    if constexpr (i > 2) {
      std::cout << "i > 2" << std::endl;
    }
    else {
      std::cout << "i <= 2" << std::endl;
    }
  };
  lambda();
}

int main()
{
  f<A<1>>();
  f<A<3>>();
  
  return 0;
}

g++ -Wall -std=c++17 -O3 -pedantic -o test test.cpp

错误是:

test.cpp: In lambda function:
test.cpp:13:24: error: lambda capture of ‘i’ is not a constant expression
   13 |     if constexpr (i > 2) {

但是,相同的代码可以在 clang++ 11.1.0 中正常编译并产生预期的结果。

哪个编译器是正确的?

【问题讨论】:

标签: c++ lambda language-lawyer constexpr


【解决方案1】:

通常您根本不需要捕获它A lambda expression can read the value of a variable without capturing it if the variable: has const non-volatile integral or enumeration type and has been initialized with a constant expression, or is constexpr and has no mutable members.

这也适用于 GCC:

auto lambda = []() {
    if constexpr (i > 2) {
      std::cout << "i > 2" << std::endl;
    }
    else {
      std::cout << "i <= 2" << std::endl;
    }
};

Try it here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 2020-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多