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

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

本文关键字:重载 函数 学习 C++ 中将 运算符 gt      更新时间:2023-10-16

我想做一个常规的运算符重载,但要使用模板。想象一下:

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

但我希望它能用于任何类或原始类。代码出了什么问题?

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

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

  2. 对于用户定义的类型,也不能以任何合理的方式重载>运算符。泛型实现无法知道如何将用户定义类型的一个实例与同一类型的另一个实例进行比较。