本文介绍了从std :: binary_function(或std :: unary function)继承的好处是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 从std :: binary_function(或std :: unary_function)继承的好处是什么?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()); } $ b ? 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和std :: unary_function在C ++ 11中已弃用。请参阅@AlexandreC的注释。std::binary_function and std::unary_function are deprecated as of C++11 see comment by @AlexandreC.推荐答案继承自[unary | binary] _function只是给你的类中另外一个typedef:Inheritance from [unary|binary]_function just gives you an additional typedefs in your class:对于unary_functionFor unary_functionargument_typeresult_type对于binary_functionFor binary_functionfirst_argument_typesecond_argument_typeresult_type你传递给[unary | binary] _function的那些类型。 在你的情况下没有好处。Which are those types you pass to [unary|binary]_function.In your case there is no benefits.如果你打算使用Functor和其他std Functors修改器,如not1,bind1st你必须继承[ unart | binart] _function。If you ever going to use your Functors with other std Functors modificators like not1, bind1st you have to inherit from [unart|binart]_function.如果你打算存储这个模板信息为你的目的,最好使用ready解决方案。And if you are going to store this template information for your purpose it is better to use ready solution. 这篇关于从std :: binary_function(或std :: unary function)继承的好处是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 08-21 12:52