使用ENABLE_IF和IS_ARITHMETIC的模板专业化
Template specialisation with enable_if and is_arithmetic for a class
我正在尝试实现具有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
};
如果您有多种可以一起处理的情况,则可以制作这些主要模板,并且只专门为剩余的特殊情况。
相关文章:
- 如何使用默认参数等选择模板专业化
- 模板化建造师专业化
- 类模板的成员功能的定义在单独的TU中完全专业化
- 部分专业化和嵌套模板
- 模板专业化可以进入我的.cpp吗?
- 别名模板的专业化 C++11 中没有开销的最佳替代方案
- 部分专业化和对标准::void_t<>的需求
- "专业化不参与超载"
- 特定好友功能专业化
- 是否可以混合使用SFINAE和模板专业化?
- 为什么在班级专业化上会出现错误?
- enable_if如何帮助选择类模板的专业化?
- std::initializer_list可以专业化吗?
- 派生类中纯虚拟基方法的专业化
- "expected a '>'"类模板专业化?
- Clang不会编译GCC会编译的模板专业化
- 我可以用clang AST从模板专业化中获得默认的模板参数吗
- 函数模板部分专业化-有什么解决方法吗
- 类模板的编译错误,但其专业化除外
- 我应该声明我的函数模板专业化还是定义它们就足够了