enable_if 和 is_arithmetic 的模板专业化 class

Template specialisation with enable_if and is_arithmetic for a class

我正在尝试实现一个具有 2 个算术类型特化的表达式 class。这是默认值 class:

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 { /* ... */ };

如果我现在编译我的代码,我会得到这个错误:

Error C3855 'Expression': template parameter '__formal' is incompatible with the declaration Vector

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

您有多个 class 主模板,这些模板无法替换。您需要有一个主要模板,然后是多个专业化。一个简单的方法是以不同的方式来做:

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

如果您有多个可以一起处理的案例,您可以制作这些主要模板,只专门化其余的特殊案例。