Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading