[英]How can I return an object with converted type from a new operator+ (Template class)
我寫了一個球體的模板類。 它保存了它們的中心點和半徑。 現在,我嘗試編寫一個operator+
,該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
iss是編譯器在其他Sphere
函數中期望的類型,所以它會給您帶來錯誤。
例子:
int number;
double(number);
要么
static_cast<double>(number);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.