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