有没有一种方法可以将整体模板参数约束为专门化,而不是这种代码冗余?
// 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> {};发布于 2017-05-25 22:21:08
您可以使用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注意,std::enable_if_t<>是一个C++14类型,它相当于
template<bool C, typename T=void>
using enable_if_t = typename std::enable_if<C,T>::type;它是如何工作的? std::enable_if的定义类似于
template<bool C, typename T=void>
struct enable_if { using type=T; };
template<typename T>
struct enable_if<false,T> {};特别是,如果条件enable_if::type为false,则不存在子类型C。因此,在上面的专门化中,enable_if_t<(N<2)>扩展为仅用于N<2的有效类型(void)。对于N>=2,我们有替换失败,因为enable_if<(N<2)>::type不存在。C++允许这样的失败,但是简单地忽略了生成的(无效)代码。
发布于 2017-05-25 22:25:50
您可以添加第二个模板参数,其默认值选择所需的专门化:
template <int N, bool = (N < 2)>
struct A {
// code for N>=2 case
};
template <int N>
struct A<N, true> {
// code for N<2 case
};(您不需要命名第二个参数,因为您永远不会显式地引用它。)
https://stackoverflow.com/questions/44190653
复制相似问题