std :: binary_function (या std :: unary_function) से विरासत का लाभ क्या है?std :: binary_function (या std :: unary function) से विरासत का लाभ क्या है?
उदाहरण के लिए मैं इस तरह के कोड है:
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());
}
लेकिन मैं यह भी विरासत रूप 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;
}
};
std :: binary_function और std :: unary_function @AlexandreC द्वारा सी ++ 11 देखते हैं कि टिप्पणी के रूप में अनुचित हैं अद्यतन किया गया। के लिए binary_function
first_argument_type
second_argument_type
result_type
कौन उन प्रकार आप पारित कर रहे हैं
लिए unary_function
argument_type
result_type
: |
से
उन्हें सी ++ 11 में बहिष्कृत कर दिया गया है (बेशक, प्रश्न पूछे जाने पर कोई सी ++ 11 नहीं था)। –
@AlexandreC। इसके बजाय हमें क्या उपयोग करना चाहिए? सी ++ कोडिंग मानकों में, एंड्रेई ने उल्लेख किया कि वे स्टर्ल एल्गोरिदम –
@kirill_igum के साथ उपयोग करने के लिए मज़ेदार बनाने के लिए महत्वपूर्ण हैं: अब 'decltype', 'auto' और' std :: result_of' उपलब्ध हैं, आपको विरासत की आवश्यकता नहीं है कुछ भी। इसके अलावा, 'बाइंड 1' और 'bind2nd' को 'बाइंड' के पक्ष में बहिष्कृत कर दिया गया है। –