C++ force compiler error if template resolution fails

Viewed 49

Based on this question I have the following templated method:

...
template <typename T>
const T& get() const {
    if constexpr ( std::is_same_v<T, C1> )
       return this->c1;
    else if constexpr( std::is_same_v<T, C2> )
       return this->c2;
    else
       throw std::logic_error("Tried to lookup from invalid type");
}

This works - but in the case of a type which is not represented in the container - e.g. Container::get<int> I would like to get a compile time error instead of the throw std::logic_error() at runtime. How can I achieve that?

1 Answers

You can add static_assert as

template<class T> struct dependent_false : std::false_type {};

template <typename T>
const T& get() const {
    if constexpr ( std::is_same_v<T, C1> )
       return this->c1;
    else if constexpr( std::is_same_v<T, C2> )
       return this->c2;
    else
       static_assert(dependent_false<T>::value, "some error message");
}
Related