Home > Software engineering >  what's the advantage of defining a class instead of a function in some c standard library?
what's the advantage of defining a class instead of a function in some c standard library?

Time:12-02

Recently I noticed that C std::less is a class,although it simply compares the values of two objects.Here is a sample code:

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

so what is the advantage of defining a class instead of a funciton? and I also wonder why using the 'const' keyword despite there is no data member in the class?

CodePudding user response:

Primarily to use it as a template parameter, like std::set<int, std::less<int>>.

Class template parameter in interfaces like std::set is used instead of pointer to function to be able to pass other function-like objects that do have some data members. In addition, making it a template parameter aids compiler optimizations, although modern compilers can optimize away function pointers in certain cases either.

  • Related