C++ check if statement can be evaluated constexpr

Here’s another solution, which is more generic (applicable to any expression, without defining a separate template each time). This solution leverages that (1) lambda expressions can be constexpr as of C++17 (2) the type of a captureless lambda is default constructible as of C++20. The idea is, the overload that returns true is selected when … Read more

“constexpr if” vs “if” with optimizations – why is “constexpr” needed?

This is easy to explain through an example. Consider struct Cat { void meow() { } }; struct Dog { void bark() { } }; and template <typename T> void pet(T x) { if(std::is_same<T, Cat>{}){ x.meow(); } else if(std::is_same<T, Dog>{}){ x.bark(); } } Invoking pet(Cat{}); pet(Dog{}); will trigger a compilation error (wandbox example), because both … Read more

Why doesn’t an if constexpr make this core constant expression error disappear?

The standard doesn’t say much about the discarded statement of an if constexpr. There are essentially two statements in [stmt.if] about these: In an enclosing template discarded statements are not instantiated. Names referenced from a discarded statement are not required ODR to be defined. Neither of these applies to your use: the compilers are correct … Read more