【发布时间】: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 中正常编译并产生预期的结果。
哪个编译器是正确的?
【问题讨论】:
-
this 会回答您的问题吗? xD
-
“哪个编译器是正确的?”类型的问题几乎总是需要“language-lawyer”标签。
标签: c++ lambda language-lawyer constexpr