Handling errors at compile time in C++

We had a discussion with colleagues on why in the following code we cannot simply use


but need to do a trick with ‘always_false’:

#include <type_traits>

struct always_false : std::false_type {};

template<typename Type>
constexpr int Get()
    if constexpr (std::is_same_v<Type, int>)
        return 1;
    else if constexpr (std::is_same_v<Type, bool>)
        return 2;
    else {
int main()
    constexpr auto result = Get<bool>(); //ok

    //compile error: static assertion failed
    //constexpr auto result = Get<float>();

    return  result;

In GCC and CLang ‘static_assert(false)’ always fails independently of Type, but in MSVC it does not.

Finally we found the answer on cppreference.com, see ‘dependent_false’.

Leave a Reply

Your email address will not be published. Required fields are marked *