mardi 5 janvier 2016

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

I wrote a template class for spheres. It saves their central point und their radius. Now i'm trying to write a new operator+ that adds a value to the every value of the central point. The call from my main function looks like this:

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

While my new operator looks like 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); // now Sphere<double, double>
        return n; //error occurs here
    }
};

The error message i get is:

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

What do i have to change that it works and why is my way wrong? Thanks for any help!

Aucun commentaire:

Enregistrer un commentaire