【问题标题】:Template specialisation with enable_if and is_arithmetic for a class具有 enable_if 和 is_arithmetic 的类的模板特化
【发布时间】:2016-12-29 20:23:56
【问题描述】:

我正在尝试实现一个具有 2 个算术类型专业化的 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<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”与声明向量不兼容

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

【问题讨论】:

  • 请分享显示相同错误的最小代码示例。根据您提供的信息,很难猜测出什么问题。
  • 我在示例代码中的任何位置都没有看到名为 __formal 的模板参数(这是一个保留标识符)或名为 Vector 的声明。请发帖minimal reproducible example

标签: c++ c++11 templates template-specialization typetraits


【解决方案1】:

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

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

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

【讨论】:

  • 感谢您的回答。多原发病例的问题就是问题!
猜你喜欢
  • 2019-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-05
  • 1970-01-01
  • 2012-08-13
  • 1970-01-01
相关资源
最近更新 更多