使用enable_if和is_arithmetic进行类的模板特化

时间:2016-12-29 20:23:57

标签: c++ c++11 templates template-specialization typetraits

我正在尝试实现一个带有2个算术类型专门化的Expression类。这是默认类:

template<typename Left, typename Op, typename Right, typename std::enable_if<!std::is_arithmetic<Left>::value, Left>::type* = nullptr>
class Expression { /* ... */ }

这是两个专业:

template<typename Left, typename Op, typename Right, typename std::enable_if<std::is_arithmetic<Left>::value, Left>::type* = nullptr>
class Expression { /* ... */ };

template<typename Left, typename Op, typename Right, typename std::enable_if<std::is_arithmetic<Right>::value, Right>::type* = nullptr>
class Expression { /* ... */ };

如果我现在编译我的代码,我会收到此错误:

  

错误C3855&#39;表达式&#39;:模板参数&#39; __ formal&#39;与声明Vector

不兼容

如何使用模板和专业化或虚拟类型来解决我的问题。

1 个答案:

答案 0 :(得分:2)

您有多个主要类模板,但这些模板无法替换。您需要有一个主模板,然后是多个特化。一种简单的方法是以不同的方式:

template<typename Left, typename Op, typename Right,
         int = std::is_arithmetic_v<Left> + 2 * std::is_arithmetic_v<Right>>
class Expression;

template <typename Left, typename Op, typename Right>
class Expression<Left, Op, Right, 0> {
    // base case
};
template <typename Left, typename Op, typename Right>
class Expression<Left, Op, Right, 1> {
    // only the left operand is arithmetic
};
template <typename Left, typename Op, typename Right>
class Expression<Left, Op, Right, 2> {
    // only the right operand is arithmetic
};
template <typename Left, typename Op, typename Right>
class Expression<Left, Op, Right, 3> {
    // both operands are arithmetic
};

如果您有多个可以一起处理的案例,您可以制作这些主要模板,并仅专门处理剩余的特殊情况。

相关问题