[英]Template specialisation with enable_if and is_arithmetic for a class
I am trying to implement a Expression class with 2 specialisation for arithmetic types. 我正在尝试实现2类专门用于算术类型的Expression类。 This is the default class:
这是默认类:
template<typename Left, typename Op, typename Right, typename std::enable_if<!std::is_arithmetic<Left>::value, Left>::type* = nullptr>
class Expression { /* ... */ }
And those are the two specialisations: 这是两个专业:
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 { /* ... */ };
If I now compile my code I get this error: 如果现在编译我的代码,则会出现此错误:
Error C3855 'Expression': template parameter '__formal' is incompatible with the declaration Vector
错误C3855'表达式':模板参数'__formal'与声明Vector不兼容
How can I solve my problem with templates and specialisation or dummy types as I used them. 在使用模板时,如何解决模板,专业化或虚拟类型的问题。
You have multiple primary class templates and these can't be replaced. 您有多个主类模板,这些模板无法替换。 You need to have one primary template followed by multiple specializations.
您需要一个主模板,然后是多个专业化模板。 A simple approach is to do it differently:
一种简单的方法是采用不同的方法:
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
};
If you have multiple cases which can be handled together you can make these primary template and only specialize the remaining special cases. 如果您有多个可以一起处理的案例,则可以制作这些主要模板,并仅对其余的特殊案例进行专业化处理。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.