I'm trying to create template Polynomical class with overloaded operator "+". I managed to make this to work with objects that are based on the same variable types (int
+ int
), but now i'm stuck with adapting this to work with objects based on different types of variables (float
+ int
).
I want to choose what kind of result i will get based on types of Polynomials i'm summing. Something like this:
float + int -> float;
float + double -> double;
int + int -> int;
unsigned int + int -> int;
And so on.
Right now i have following code:
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);
}
And this is my attempt to create neccesary functionality
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));
}
But if i use this i will get Polynominal based on first one's type in binary expression, and that not what i need.
Finalizing question: Is it possible to create binary operator that returns result based on operand's types but without taking their order in account. (Since it works with simple numberical types it is possible, but i have no idea how to make this work)
I'm storing coefficient of polynominal in std::vector<ScalarType>
Here is full class code