如果 lhs 或 rhs 对象是浮点数,则 operator+ 的结果是浮点数

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

所以我写了一个简单的模板class,它存储一个数组。我正在尝试重载 + 运算符,以便它逐个元素地对两个对象的数组求和。它工作正常,但这是问题所在。

我希望这样,如果 lhsrhs(或两者)对象是浮点类型,则结果也将是浮点对象。

例如:testclass({1, 2, 3}) + testclass({2.2, 3.3, 1.1}) 会 return 一个 testclass<double> 对象。

如果 rhs 对象是双精度的,我设法让它工作,但是当 lhs 是双精度的时候我就无法正常工作。

这是我到目前为止编写的代码:

#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();
}

使用decltype检查表达式的类型:

testclass<decltype(this->data[0] + rhs.data[0])> ret;