如何从新运算符+(Template类)返回具有转换类型的对象

How can I return an object with converted type from a new operator+ (Template class)

本文关键字:返回 转换 类型 对象 运算符 Template      更新时间:2023-10-16

我为球体编写了一个模板类。它保存了它们的中心点和半径。现在,我正在尝试编写一个operator+,它为中心点的每个值添加一个值。我的主函数调用如下:

Sphere<int, double> s1(1,1,1,2.5); // (x,y,z,radius)
auto s2 = s1 + 1.5;

而我的operator+看起来是这样的:

template <typename T, typename S> class Sphere { 
...
    template <typename U>
    friend Sphere operator+(const Sphere<T, S> s, U add){ // Sphere<int, double>
        decltype(s.m_x + add) x,y,z;
        x = s.m_x + add;
        y = s.m_y + add;
        z = s.m_z + add;
        Sphere<decltype(x), S> n(x,y,z,s.rad); // now Sphere<double, double>
        return n; //error occurs here
    }
};

我得到的错误消息是:

could not convert 'n' from 'Sphere<double, double>' to 'Sphere<int, double>'

我必须改变什么才能奏效?为什么我的方法错了?

friend函数的返回类型中的Sphere指的是封闭类的类型,因此它是Sphere<int, double>。使用尾部返回类型指定正确的类型

template <typename U>
friend auto operator+(Sphere<T, S> const& s, U add)
    -> Sphere<decltype(s.m_x + add), S>
{ ... }

或者,如果您有一个支持函数推导返回类型的C++14编译器,那么只需删除尾部返回类型即可。

template <typename U>
friend auto operator+(Sphere<T, S> const& s, U add)
{ ... }

因此,在您的示例中,您有return n,n由Sphere<int, double>Sphere<double, double>组成。它会给您错误,因为您的值类型为int,而double是编译器在其他Sphere函数中期望的类型。

示例:

int number;
double(number);

static_cast<double>(number);