gpt4 book ai didi

c++ - 如何从新的 operator+(模板类)返回具有转换类型的对象

转载 作者:行者123 更新时间:2023-11-30 01:45:27 25 4
gpt4 key购买 nike

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

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>'

我必须改变什么才能让它起作用,为什么我的方法不对?

最佳答案

Sphere在你的friend函数的返回类型指的是封闭类的类型,所以它是 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)
{ ... }

关于c++ - 如何从新的 operator+(模板类)返回具有转换类型的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34622518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com