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); }
[x],[&x],[&], ...), and it is related toynot beingconstexpranymore at some point, sol() - 1is not a compile-time expression and the compilation fails.l() - 1a constant expression in this context.l() - 1should be reallyconstexpr.l() - 1gives a constexpr with the following line inmain():constexpr auto z = l2() - 1;foo<decltype(l2)>is instantiated, the parameterlis a reference that has not been initialised with a constant expression. References that have not been initialised with a constant expression cannot be used in constant expressions.