Search code examples
c++constexprstatic-assert

If constexpr compile time crash for wrong branch


I have a serialization function that does something like:

class Serializer
{
    template<typename T>
    T read(const std::string& source)
    {
        if constexpr(std::is_same<T, int>::value)
        {
            return std::stoi(source);
        }
        else if constexpr(std::is_same<T, float>::value)
        {
            return std::stof(source);
        }
        else
        {
            assert(false);
            return T();
        }
    }
};

What I would like to do is replace the run-time assert with a compile-time assert (like static_assert), to detect that an implementation is missing at compile-time. Full function specialization would be an option to detect a missing implementation, but that is not really an option for me because it is a member function which might require a bunch of members from the encapsulating class. Is there any way to do something like a static assert that does not get triggered if the constexpr branch is not hit?


Solution

  • Since static_assert(false); does not depend on the template parameters, the compiler can check this assertion before the point of instantiation in the two phase lookup. Thus, for instance, the following static_assert correctly works for your purpose:

    DEMO

    class Serializer
    {
    public:    
        template<typename T>
        T read(const std::string& source)
        {        
            if constexpr(std::is_same<T, int>::value)
            {
                return std::stoi(source);
            }
            else if constexpr(std::is_same<T, float>::value)
            {
                return std::stof(source);
            }
            else
            {
                static_assert(!std::is_same<T, T>::value);
            }
        }
    };