vendredi 30 octobre 2015

Result from operator+ to be floating-point if either lhs or rhs object is floating-point

So I have written a simple template class which stores an array. I'm trying to overload the + operator so that it sums up two objects' arrays element by element. It works fine, but here is the problem.

I want it to be so that if either the lhs or rhs (or both) object is of a floating-point type, the result would also be a floating-point object.

For example: testclass({1, 2, 3}) + testclass({2.2, 3.3, 1.1}) would return a testclass<double> object.

I managed to get it to work if the rhs object is double, but can't get it right when lhs is double.

This is the code I have written so 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 i = 0;
        for (const T &el : ilist) this->data[i++] = el;
    }

    auto &operator[](const short &i) { return this->data[i]; }

    //so when this is called the return object would be the same
    //type as the rhs object
    template<class type_t>
    auto operator+(const testclass<type_t> &rhs)
    {
        testclass<type_t> ret;
        for (short i = 0; i < 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;

    for (short i = 0; i < 4; ++i) 
        std::cout << res[i] << " ";

    std::cin.get();
}

Aucun commentaire:

Enregistrer un commentaire