This question Access to constexpr variable inside lambda expression without capturing answered why the ref-capture in the below example isn't strictly neccessary. But on the other hand one gets an error, if it is captured.
The error seems to be triggered by the recursive nature of foo()
.
template<typename T>
constexpr int bar(const T& x) { // NOK
//constexpr int bar(T x) { // OK
return x;
}
template<typename T>
int foo(const T& l) {
constexpr auto x = l() - 1;
auto y = [&]{return bar(x);}; // if ref-capture is used, the above bar(const T&) is NOK, why?
if constexpr(x <= 0) {
return 42;
}
else {
return foo(y);
}
}
auto l2 = []{
return 3;
};
int main() {
foo(l2);
}