简体   繁体   中英

Declaration of overload operator- of objects with 2 different types

I have a template-class and wrote a operator- which should do the math with 2 objects of different type and return it as a new object. Now i'm wondering how can i declare this operator- in my class, since something like

template<typename S> 
friend auto operator-(const XY<T>,const XY<S>)->XY<decltype(T-S)>; 

isn't allowed? Here is my example code:

template <typename T>
class XY{
private:
    T x

...

// template<typename S> 
// friend auto operator-(const XY<T>, const XY<S>)->XY<decltype(T-S)>;

};

template <typename T, typename S>
auto operator-(const XY<T> z1, const XY<S> z2)->XY<decltype(z1.x - z2.x)>{
    decltype(z1.x - z2.x) x;
    x = (z1.x - z2.x);
    XY<decltype(x)> n(x);

    return n;
}

Is this what you are looking for?

template <typename T>
class XY{
private:
    T x;

template <typename U, typename S>
friend auto operator-(const XY<U> z1, const XY<S> z2)->XY<decltype(z1.x - z2.x)>;

};

template <typename T, typename S>
auto operator-(const XY<T> z1, const XY<S> z2)->XY<decltype(z1.x - z2.x)>{...}

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM