c++lambdalanguage-lawyerc++20constexpr

get constexpr variable from a lambda function is fine , but compile fail (Visual C++) and fine (gcc) when such statement is in a new lambda


This code compiles fine in gcc, but fail in Visual C++.

MCVE = https://wandbox.org/permlink/SqNI85EospSrwm5T

int main() {
    auto func_do1Pass2=[&]() {
        return 8;
    };
    constexpr int g=func_do1Pass2();
    auto sLambda=[&]() {
        constexpr int g2=func_do1Pass2();  //<== error at Visual C++
    };
}

Error C2131 expression did not evaluate to a constant

  1. Who is wrong? Why? Please give reference.

  2. Here is my more real example. What is a workaround for the below code in Visual C++ case?

Code:

void testtt() {
    auto func_do1Pass2=[&]<int s>() {
        return 8;
    };
    [&]<int s2>() {
        ///vvv can edit only here
        constexpr int g2=func_do1Pass2.operator()<s2>();
        ///^^^ can edit only here
    }.operator()<2>();
}

Solution

  • Just make func_do1Pass2 constexpr as shown below. The problem is that in your given code func_do1Pass2 isn't constexpr so it can't be used in constexpr context.

    void testtt() {
    //--vvvvvvvvv-------------------------------->added constexpr here
        constexpr auto func_do1Pass2=[&]<int s>()  {
            return 8;
        };
        [&]<int s2>() {
            
            constexpr int g2=func_do1Pass2.operator()<s2>();
            
        }.operator()<2>();
    }
    

    Working demo