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


i wrote template class spheres. saves central point , radius. i'm trying write operator+ adds value every value of central point. call main function looks this:

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

while operator+ looks this:

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); // sphere<double, double>         return n; //error occurs here     } }; 

the error message is:

could not convert 'n' 'sphere<double, double>' 'sphere<int, double>' 

what have change works , why way wrong?

the sphere in friend function's return type refers type of enclosing class, it's sphere<int, double>. use trailing return type specify correct type

template <typename u> friend auto operator+(sphere<t, s> const& s, u add)     -> sphere<decltype(s.m_x + add), s> { ... } 

or if have c++14 compiler supports deduced return types functions, drop trailing return type.

template <typename u> friend auto operator+(sphere<t, s> const& s, u add) { ... } 

Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -