Search code examples
c++constantsc++20constexpr

Initializing constant variable based on constexpr condition


How can I initialize constant variable based on constexpr condition?

I need initialization equivalent to this non-compilable code:

const int x;
if constexpr(cond)
    x = value1; // value1 may not be valid if cond is false
else        
    x = value2; // value2 may not be valid if cond is true

Solution

  • constexpr int x = []{
        if constexpr (cond)
            return value1;
        else        
            return value2;
    }();