【问题标题】:operator overloading using template使用模板重载运算符
【发布时间】:2018-08-03 17:35:46
【问题描述】:

我正在编写一个名为 Double 的类,它扩展了 C++ 中的内置类型“double”。它有一个“double”类型的数据成员。对于 Double 类,我需要重载许多基本算术运算符,例如“+”、“-”、“*”、“/”。例如,“+”运算符是这样重载的:

Relation<Double>* operator+ (Double &d2)   
// Relation is a abstract class template.
{
   /*
   ...code that do something else.
   */ 
   return new Plus<Double>(this, &d2);   // Plus is derived from Relation.
}                             
// Double + Double returns a Relation pointer.

并且“-”运算符以同样的方式快速重载:

Relation<Double>* operator- (Double &d2)
{
   /*
   ...code that do something else but the same as above.
   */ 
   return new Minus<Double>(this, &d2);
}

实际计算由Relation类中的成员函数完成。运算符主体的唯一区别是初始化的对象(Plus vs Minus)。 对于恰好采用两个操作数的运算符,我应该总是像这样进行重载,这是重复的并且不好。 所以我想到了模板功能。但问题是,我可以传递 PlusMinus 作为模板参数,但不能传递运算符。如何制作模板或使用其他方法来重载这些运算符?

【问题讨论】:

  • 您似乎在解析一些表达式。但是在那种情况下,为什么要使用运算符重载呢?
  • @liliscent 因为我想启用这样的表达式:Double + Double - Double。然后将这些关系保存到“关系”类。
  • 不完全清楚,但如果 do something else 对于许多操作员来说是相同的,它看起来应该委托给一个单独的函数。您将拥有运算符声明(您无法取消),一个函数调用和一个返回。对我来说看起来很干净。

标签: c++ templates operator-overloading template-function


【解决方案1】:

是的,运算符重载可能是一个痛苦和代码重复的根源,请参阅this suggestion to the standard 以缓解它。

目前我唯一能想到的是这样的:

template<typename T>
struct OperatorMinus {
  static T doIt(T const& lhs, T const& rhs) { return lhs - rhs; };
}

template<typename T>
struct OperatorPlus {
  static T doIt(T const& lhs, T const& rhs) { return lhs + rhs; };
}

template<typename T, typename U>
class Operator: public Relation<T>
  public:
  Operator(T const& lhs, T const& rhs): _lhs(lhs), _rhs(rhs) {}

  T doIt() override {
    return U::doIt(_lhs, _rhs);
  }

  private:
  T _lhs;
  T _rhs;
};

Relation<Double>* operator+ (Double &d2)   
{
   return new Operator<Double, OperatorPlus<Double>>(this, &d2);
}   

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 2023-03-03
    • 2015-09-15
    • 1970-01-01
    • 1970-01-01
    • 2022-10-01
    • 1970-01-01
    相关资源
    最近更新 更多