如果模板解析失败,c++强制编译器错误



基于这个问题,我有以下模板化方法:

...
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");
}

这是有效的-但是在容器中没有表示的类型的情况下-例如Container::get<int>,我希望在运行时获得编译时错误而不是throw std::logic_error()。我怎样才能做到呢?

可以添加static_assert

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");
}

最新更新