gpt4 book ai didi

c++ - 从 std::binary_function (或 std::unary 函数)继承有什么好处?

转载 作者:IT老高 更新时间:2023-10-28 12:50:08 26 4
gpt4 key购买 nike

从 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 自 C++11 起已弃用,请参阅@AlexandreC 的评论。

最佳答案

从 [unary|binary]_function 继承只是在你的类中给你一个额外的 typedef:

对于一元函数

argument_type
result_type

对于二进制函数

first_argument_type
second_argument_type
result_type

您传递给 [unary|binary]_function 的那些类型是什么。在你的情况下,没有任何好处。

如果您打算将您的 Functor 与其他 std Functor 修饰符(例如 not1、bind1st)一起使用,您必须从 [unart|binart]_function 继承。

如果您要为您的目的存储此模板信息,最好使用现成的解决方案。

关于c++ - 从 std::binary_function (或 std::unary 函数)继承有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/609937/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com