声明重载运算符 - 具有 2 种不同类型的对象

Declaration of overload operator- of objects with 2 different types

本文关键字:同类型 对象 重载 运算符 具有 声明      更新时间:2023-10-16

我有一个模板类并编写了一个运算符 - 它应该对 2 个不同类型的对象进行数学运算并将其作为新对象返回。现在我想知道我如何在我的类中声明这个运算符,因为类似

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

不允许?这是我的示例代码:

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;
}

这是你要找的吗?

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)>{...}

演示