标准运算符的函数指针

function pointers of standard operators

本文关键字:指针 函数 运算符 标准      更新时间:2023-10-16

这是一个后续问题,函数指针使用"<"作为运算符,仍然没有答案。

这与我在这里找到的答案代码非常相似:是否可以获取内置标准运算符的功能指针?

问。在上面的链接中+被用作std::operator+那么为什么我不能使用std::operator<呢?

目的是不要使用参数较少的重载函数,而是用std::library中的某些内容替换

template <typename T>
bool compare (T a,T b,bool (*compareFunction) (T ,T ))
{
    return compareFunction (a,b);
}
template <typename T>
bool compare (T a,T b)
{
    return a<b;
}
bool m (int a ,int b)
{
    return a<b;
}
int main ()
{
    int a=5,b=6;
    /*
    * This Works
    */
    if (compare<int>(a,b,m))
        cout<<"Sucess";
    else        
        cout<<"Post this in stack overflow ";
    /*
    * This also Works
    */
    if (compare<int>(a,b))
        cout<<"Sucess";
    else
        cout<<"Post this in stack overflow ";
    /*
    * Adding this gives compile error.
    */
    if (compare<int> (a,b,&std::operator<))
        cout<<"sucess";
    else
        cout<<"Post in Stackoverflow "; 
return 0;
}

您必须区分内置运算符和重载运算符。内置运算符是仅具有基本类型(整数、布尔值、浮点数、指针(的操作数的运算符。

例如:

int a = 9, b = 7;
a + b; <-- built-in plus operator
6 + 5; <-- built-in plus operator

C++提供了为用户定义类型(即类(定义运算符的可能性。 std::string是一个类(由库定义,但这并不重要(。所以如果我们写这个:

std::string a = "asdf", b = "qwert";
a + b; <-- this is not built-in operator.

为了使上述内容进行编译,必须有一个加号运算符的声明和定义,该运算符对字符串类型的两个对象进行操作。碰巧标准库定义了这样的运算符:std::operator+(std::basic_string(。所以这个:

std::string a = "asdf", b = "qwert";
a + b;

其实是这样的:

std::string a = "asdf", b = "qwert";
std::operator+(a, b); <-- call to overloaded operator (see this as a function call)

内置运算符不是函数。重载运算符的行为类似于函数。
内置运算符只有基本类型作为操作数,其功能由标准定义(不能重新定义int + int的作用(。
重载运算符必须至少有一个用户定义类型的操作数。


让我们来看看一些实际的例子:

template <class T, class Compare>
bool compare (T a, T b, Compare comp) {
   return comp(a,b);
}

我已将您的函数指针替换为模板参数。因此,这可以是函数指针、函数引用或函数对象。

你有什么选择来称呼它,Tint?好吧,您当然不能让操作员通过comp.所以你必须有一个函数或一个函数对象(见下面的链接(。

// function
bool intCompareLess(int a, int b) {
  return a < b;
}
compare(3, 5, intCompareLess);

// function object
class IntComparatorLess {
public:
   // this is a function call operator overload
   bool operator()(int a, int b) {
      return a < b;
   }
};
compare(3, 5, IntComparatorLess());
// or don't reinvent the wheel:
compare(3, 5, std::less<int>()); // std::less is somehow similar with IntComparatorLess

如果将比较与T称为用户定义类型,该怎么办

class MyClass {
public:
  int x, y;
};

现在你有一个额外的选择:定义一个运算符并将其作为参数传递:

bool operator<(MyClass c1, MyClass c2) {
  if (c1.x == c2.x) 
    return c1.y < c2.y;
  return c1.x < c1.x
}
MyClass a, b;
compare(a, b, (bool (*)(MyClass, MyClass))operator<);

有用: C++函子 - 及其用途