c++ - Result from operator+ to be floating-point if either lhs or rhs object is floating-point -
so have written simple template class stores array. i'm trying overload +
operator sums 2 objects' arrays element element. works fine, here problem.
i want if either lhs
or rhs
(or both) object of floating-point type, result floating-point object.
for example: testclass({1, 2, 3}) + testclass({2.2, 3.3, 1.1})
return testclass<double>
object.
i managed work if rhs
object double, can't right when lhs
double.
this code have written far:
#include <iostream> #include <initializer_list> template<class t> class testclass { public: t data[4]; public: testclass() {} testclass(const std::initializer_list<t> &ilist) { short = 0; (const t &el : ilist) this->data[i++] = el; } auto &operator[](const short &i) { return this->data[i]; } //so when called return object same //type rhs object template<class type_t> auto operator+(const testclass<type_t> &rhs) { testclass<type_t> ret; (short = 0; < 4; ++i) ret.data[i] = this->data[i] + rhs.data[i]; return ret; } }; int main() { testclass<int> obj = { 1, 2, 3, 4 }; testclass<double> obj2 = { 1.1, 2.2, 3.3, 4.4 }; auto res = obj2 + obj; (short = 0; < 4; ++i) std::cout << res[i] << " "; std::cin.get(); }
use decltype
check type of expression:
testclass<decltype(this->data[0] + rhs.data[0])> ret;
Comments
Post a Comment