What is the benefit of inheriting from std::binary_function (or std::unary_function)?
For example I have such code:
class Person { public: Person(); Person(int a, std::string n); Person(const Person& src); int age; std::string name; }; Person::Person() : age(0) , name('') {}; Person::Person(int a, std::string n) : age(a) , name(n) {}; Person::Person(const Person& src) { age = src.age; name = src.name; }; struct PersonPrint : public std::unary_function<Person, void>{ void operator() (Person p){ std::cout << ' Person age: ' << p.age << ' name: ' << p.name << std::endl; } }; struct PersonGreater : public std::binary_function<Person, Person, bool>{ bool operator()(const Person& p1, const Person p2){ if (p1.age > p2.age) return true; if (p1.name.compare(p2.name) > 0) return true; return false; } }; int main(int count, char** args) { std::vector<Person> personVec; Person p1(10, 'Person1'); Person p2(12, 'Person2'); Person p3(12, 'Person3'); personVec.push_back(p1); personVec.push_back(p2); personVec.push_back(p3); std::cout << 'before sort: ' << std::endl; std::for_each(personVec.begin(), personVec.end(), PersonPrint()); std::sort(personVec.begin(), personVec.end(), PersonGreater()); std::cout << 'after: ' << std::endl; std::for_each(personVec.begin(), personVec.end(), PersonPrint()); }
But I also could write this code without inheritance form std::unary_function/std::binary_function?
struct PersonPrint { void operator() (Person p) { std::cout << ' Person age: ' << p.age << ' name: ' << p.name << std::endl; } }; struct PersonGreater { bool operator()(const Person& p1, const Person p2) { if (p1.age > p2.age) return true; if (p1.name.compare(p2.name) > 0) return true; return false; } };
UPDATED
std::binary_function and std::unary_function are deprecated as of C++11 see comment by @AlexandreC.
Inheritance from [unary|binary]_function just gives you an additional typedefs in your class:
For unary_function
For binary_function
Which are those types you pass to [unary|binary]_function. In your case there is no benefits.
If you ever going to use your Functors with other std Functors modificators like not1, bind1st you have to inherit from [unart|binart]_function.
And if you are going to store this template information for your purpose it is better to use ready solution.