stop visual studio 17 compile when i hit a bad constexpr if branch

213 views Asked by At

Is there any way to force the compiler to fail if a constexpr if branch is not supposed to be hit?

this code below explains it all better than I could:

template<unsigned int number_base>
class arithmetic_type
{
    if constexpr(number_base == 0 || number_base == 1)
    {
        //hey, compiler! fail this compilation please
    }
    else
    {
        //go on with class implementation
    }

}
1

There are 1 answers

2
Barry On BEST ANSWER

You want static_assert(). In this case, you can drop the if constexpr and just assert directly:

template<unsigned int number_base>
class arithmetic_type
{
    static_assert(number_base != 0 && number_base != 1); // or >= 2, since unsigned
    //go on with class implementation
};

But generally, there may be places where you just need static_assert(false). But that is ill-formed, that assertion would always trigger because it's a non-dependent conditional. In that case, you need to provide something that looks dependent but actually isn't:

// always false, but could hypothetically be specialized to be true, but 
// nobody should ever do this
template <class T> struct always_false : std::false_type { };

static_assert(always_false<SomeDependentType>::value);