Mr Z Mr Z - 19 days ago 7
C++ Question

How to avoid warning about no return expression when using static_assert?

I have two libraries that I work with and I wrote a converter between some of the types/structs they use, for convenience.

template<typename T>
struct unsupportedType : std::false_type
{};

template<typename T>
FormatB getFormat()
{
static_assert(
unsupportedType<T>::value, "This is not supported!");
}

template<>
FormatB getFormat<FormatA::type1>()
{
return FormatB(//some parameters);
}

template<>
FormatB getFormat<FormatA::type2>()
{
return FormatB(//some other parameters);
}


Now due to the unsupportedType struct, the compiler does not immediately see that the assertion will always fail and thus does not throw a compilation error if the non-specialized version is not called somewhere. However, the compiler therefore also does not know that a return statement after the static_assert is unnecessary. I do not just want to place an arbitrary return statement after the assert to get rid of the warning.

Question: What is a clean way to get rid of the warning?

Answer

There's more than one way to exit a function, returning is one, but throwing is another:

template<typename T>
FormatB getFormat()
{
    static_assert(
        unsupportedType<T>::value, "This is not supported!");
    throw 0; // Unreachable
}