在某些 C++ 标准库中定义类而不是函数有什么好处?

li *_*iao 4 c++ oop stl

最近我注意到 C++ std::less 是一个类,尽管它只是比较两个对象的值。下面是示例代码:

template <class T> struct less {
  bool operator() (const T& x, const T& y) const {return x<y;}
  typedef T first_argument_type;
  typedef T second_argument_type;
  typedef bool result_type;
};
Run Code Online (Sandbox Code Playgroud)

那么定义类而不是函数有什么好处呢?我还想知道为什么尽管类中没有数据成员却使用“const”关键字?

Ale*_*iev 5

主要将其用作模板参数,例如std::set<int, std::less<int>>.

接口中的类模板参数std::set用于代替函数指针,以便能够传递其他具有某些数据成员的类似函数的对象。此外,使其成为模板参数有助于编译器优化,尽管现代编译器在某些情况下也可以优化函数指针。