二进制运算符重载

时间:2017-12-16 12:14:00

标签: c++ oop c++11 templates stl

我正在尝试使用重载运算符“+”创建模板Polynomical类。我设法使这与基于相同变量类型(int + int)的对象一起工作,但现在我仍然坚持使用它来处理基于不同类型变量的对象(float + int)。 我想根据我总结的多项式的类型选择我将得到什么样的结果。像这样:

float + int -> float;
float + double -> double;
int + int -> int;
unsigned int + int -> int;

等等。

现在我有以下代码:

    template <class ScalarType>
    class Polynomial {

    public:
      Polynomial<ScalarType> operator+ (const Polynomial<ScalarType>& other) const;

}

template <class ScalarType>
Polynomial<ScalarType> Polynomial<ScalarType>::operator+ (const Polynomial<ScalarType>& other) const {
  bool firstIsMore = this->size() > other.size();
  Polynomial<ScalarType> result(firstIsMore ? *this : other);

  typename std::vector<ScalarType>::iterator resultIt = result.nc_begin();
  typename std::vector<ScalarType>::const_iterator summIterBegin = (firstIsMore ? other.begin() : this->begin());
  typename std::vector<ScalarType>::const_iterator summIterEnd = (firstIsMore ? other.end() : this->end());

  while (summIterBegin != summIterEnd) {
    *resultIt += *summIterBegin;
    resultIt++;
    summIterBegin++;
  }

  return(result);
}

这是我尝试创建必要的功能

  template <class OtherScalar>
  Polynomial<ScalarType> operator+ (const Polynomial<OtherScalar>& other) const;


template <class ScalarType>
class Polynomial {

public:

  template <class OtherScalar>
  Polynomial<ScalarType> operator+ (const Polynomial<OtherScalar>& other) const;

}

template <class ScalarType>
template <class OtherScalar>
Polynomial<ScalarType> Polynomial<ScalarType>::operator+ (const Polynomial<OtherScalar>& other) const {

  std::vector<ScalarType> summResult = this->getCoefficients();
  std::vector<OtherScalar> toSumm = other.getCoefficients();

  std::transform(summResult.begin(),
                 summResult.end(),
                 toSumm.begin(),
                 summResult.begin(),
                 [](const ScalarType& first, const OtherScalar& second){return (first + second);});

  if (summResult.size() < toSumm.size()) {
    summResult.insert(summResult.end(), toSumm.begin() + (toSumm.size() - summResult.size()), toSumm.end());
  }

  return(Polynomial(summResult));
}

但是,如果我使用这个,我将根据二元表达式中的第一个类型得到多项式,而这不是我需要的。

最终问题:是否可以创建二元运算符,该运算符根据操作数的类型返回结果,但不考虑其订单。 (因为它适用于简单的数字类型,这是可能的,但我不知道如何使这项工作)

我在std::vector<ScalarType>中存储多项式系数 Here是完整的类代码

1 个答案:

答案 0 :(得分:1)

我认为decltype()可以帮到你。

这样的东西
template <class OtherScalar>
Polynomial<decltype(ScalarType()+OtherScalar())> operator+
   (const Polynomial<OtherScalar>& other) const;

ps:警告:未经测试

相关问题