2

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?

user422005
  • 1,989
  • 16
  • 34
  • 1
    `static_assert(std::is_same_v || std::is_same_v)` as first line of `get` definition ? – rafix07 Feb 01 '21 at 09:41
  • https://stackoverflow.com/questions/53945490/how-to-assert-that-a-constexpr-if-else-clause-never-happen – Mat Feb 01 '21 at 09:43

1 Answers1

2

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");
}
songyuanyao
  • 169,198
  • 16
  • 310
  • 405