【发布时间】:2017-12-16 12:14:00
【问题描述】:
我正在尝试使用重载运算符“+”创建模板多项式类。我设法使它适用于基于相同变量类型的对象(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 是完整的类代码
【问题讨论】:
-
没有阅读整篇文章,但您可能会发现
std::common_type很有用。
标签: c++ oop c++11 templates stl