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