如何在 C++ 中将 > 运算符正确重载为模板函数?学习模板重载

How can I properly overload the > operator as a template function in C++? Learning template overloading

我想进行常规运算符重载,但要使用模板。所以想象一下:

template <typename Type>
bool operator> (Type &tX, Type &tY)
{
     return (tX.data > tY.data) ? tX : tY;
}

但我希望它能与任何 class 或原语一起使用。代码有什么问题?

How can I properly overload the > operator as a template function in C++?

  1. 您不能为原始类型重载 > 运算符。语言不允许这样。

  2. 您也不能以任何明智的方式为用户定义的类型重载 > 运算符。通用实现无法知道如何将用户定义类型的一个实例与同一类型的另一个实例进行比较。