0

When I try to compile the following code using clang the static assertion fails:

#include <type_traits>

template<typename T>
int TypeTest()
{
    if constexpr (std::is_same_v<bool, T>) {
        return 1;
    } else if constexpr (std::is_same_v<std::uint8_t, T>) {
        return 2;
    } else {
        static_assert(false, "check");

        return 3;
    }
}

int main()
{
    return TypeTest<bool>();
}

It even fails if there is no TypeTest is not used at all in the code. Can anybody tell me how the compiler arrives at the static assert during compile time?

3
  • 1
    Would be good in C++23 :-) Commented Aug 30, 2023 at 13:07
  • Personally I almost never use if constexpr to detect template types. I would rather use template specialization, and then let the compiler detect the missing template implementation by itself for unsupported types. Commented Aug 30, 2023 at 13:08
  • 1
    @Someprogrammerdude: for types, it is indeed not needed, for more generic traits (which might overlap)(and with "priority") , if constexpr is simpler: avoid the combination and repeting preceding negated condition. Commented Aug 30, 2023 at 13:20

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.