使用ENABLE_IF和IS_ARITHMETIC的模板专业化

Template specialisation with enable_if and is_arithmetic for a class

本文关键字:ARITHMETIC 专业化 IS ENABLE IF 使用      更新时间:2023-10-16

我正在尝试实现具有2种专业化算术类型的表达类。这是默认类:

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'表达式':模板参数'__formal'与声明矢量

不相容

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

您有多个主要类模板,这些模板无法替换。您需要有一个主模板,然后进行多个专业。一种简单的方法是做不同的方法:

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

如果您有多种可以一起处理的情况,则可以制作这些主要模板,并且只专门为剩余的特殊情况。