c++ - 使用 gcc 捕获 lambda 错误,使用 clang 进行编译

标签 c++ lambda language-lawyer constexpr

以下程序不能用 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 上编译得很好,并产生了预期的结果。
哪个编译器是正确的?

最佳答案

通常你会根本不需要捕获它 : 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.

关于c++ - 使用 gcc 捕获 lambda 错误,使用 clang 进行编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67350629/

相关文章:

c++ - 为什么 C++1 1's lambda require "mutable"关键字默认用于按值捕获?

java - 使用 lambda 表达式转换 List

scala - 有没有办法在 Scala 中匹配(switch case)lambda 表达式?

c++ - Clang 拒绝仅通过专门化定义类模板的嵌套类的代码是否正确?

c++ - 将带有模板的自定义类插入 std::map

c++ - XCode 中的字符串 (C++)

c++ - 从 native C/C++ 生成并运行 LLVM 代码

c++ - 运行时的虚函数调用(std c++)

c - memcmp 应该返回什么?

c++ - C++11 标准中的核心常量表达式是什么?