有没有办法将整数模板参数限制为专门化而不是代码冗余?
// redundant code
template <int N>
struct A {};
template <>
struct A <0> {};
template <>
struct A <1> {};
// what i want is some thing like this
template <int N>
struct A {};
template <>
struct A <N < 2> {};
Run Code Online (Sandbox Code Playgroud)
您可以使用SFINAE ="替换失败不是错误".例如,有几种方法可以在这里完成
template<int N, typename E=void>
struct A { /* ... */ }; // general type
template<int N>
struct A<N, std::enable_if_t<(N<2)> >
{ /* ... */ }; // specialisation for N<2
Run Code Online (Sandbox Code Playgroud)
注意,这std::enable_if_t<>是一个C++ 14类型,它相当于
template<bool C, typename T=void>
using enable_if_t = typename std::enable_if<C,T>::type;
Run Code Online (Sandbox Code Playgroud)
它是如何工作的?定义std::enable_if类似于
template<bool C, typename T=void>
struct enable_if { using type=T; };
template<typename T>
struct enable_if<false,T> {};
Run Code Online (Sandbox Code Playgroud)
特别是,enable_if::type如果条件C为假,则没有子类型.因此,在上面的特化中,仅enable_if_t<(N<2)>扩展为有效类型(void)N<2.因为N>=2,我们有替换失败,因为enable_if<(N<2)>::type不存在.C++允许这样的失败,但只是忽略了生成的(无效的)代码.