在模板特化中强制编译时错误

Mai*_*ein 6 c++ templates template-meta-programming c++11

我最近开始学习现代模板元编程,我自己写了一个index_of函数用于类型.

template<std::size_t Index, class C, class A> struct mp_index_of_impl{};
template<std::size_t Index, class C,template<class...> class A,class ...Ts>
struct mp_index_of_impl<Index,C,A<C,Ts...>>{
    using type = std::integral_constant<std::size_t,Index>;
};
template<std::size_t Index, class C,template<class...> class A,class ...Ts,class T1>
struct mp_index_of_impl<Index,C,A<T1,Ts...>>{
    using type = typename mp_index_of_impl<Index + 1,C,A<Ts...>>::type;
};
template<std::size_t Index, class C,template<class...> class A> struct mp_index_of_impl<Index,C,A<>>{
    //static_assert(false,"Does not contain type");
    using type = std::integral_constant<std::size_t,0>;
};
Run Code Online (Sandbox Code Playgroud)

问题是我上次的专业化

template<std::size_t Index, class C,template<class...> class A> 
struct mp_index_of_impl<Index,C,A<>>{
      //throw a compile error here
};
Run Code Online (Sandbox Code Playgroud)

我试着像这样使用static_assert

template<std::size_t Index, class C,template<class...> class A> struct mp_index_of_impl<Index,C,A<>>{
    static_assert(false,"Does not contain type");
};
Run Code Online (Sandbox Code Playgroud)

但是每次都会抛出一个编译错误,即使它不匹配.

如果匹配此模板特化,我想抛出一个带有自定义错误消息的编译错误.我该怎么做?

Tar*_*ama 10

如果你static_assert(false,...)在一个模板专门化中,那么总是不可能从中生成有效的代码.这是不正确的,不需要诊断.

解决此问题的方法是使您static_assert依赖模板参数:

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

template <typename T>
inline T getValue(AnObject&)
{
    static_assert( assert_false<T>::value , "Does not contain type");
}
Run Code Online (Sandbox Code Playgroud)