首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用enable_if和is_arithmetic对类进行模板专门化

用enable_if和is_arithmetic对类进行模板专门化
EN

Stack Overflow用户
提问于 2016-12-29 20:23:56
回答 1查看 1.8K关注 0票数 1

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

代码语言:javascript
复制
template<typename Left, typename Op, typename Right, typename std::enable_if<!std::is_arithmetic<Left>::value, Left>::type* = nullptr>
class Expression { /* ... */ }

这是两个特例:

代码语言:javascript
复制
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‘与声明向量不兼容

我如何解决我的问题,模板和专业化或虚拟类型,因为我使用它们。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-12-29 20:36:39

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

代码语言:javascript
复制
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
};

如果您有多个可以一起处理的案例,则可以生成这些主模板,并且只专门处理其余的特殊情况。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41386688

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档