STD ::功能和std :: mem_fn有什么区别

What is the difference between std::function and std::mem_fn

本文关键字:fn 区别 什么 mem 功能 std STD      更新时间:2023-10-16

我在找出两个函数包装器std::functionstd::mem_fn之间的区别时遇到了麻烦。从描述来看,在我看来,std ::函数可以完成std::mem_fn的所有功能。在哪种情况下,将在std::function上使用std::mem_fn

您无法真正将std::functionstd::mem_fn进行比较。前者是一个类模板,其类型是您指定的类型,后者是具有未指定返回类型的函数模板。实际上,您实际上并没有考虑到一个情况与另一个情况。

可以在mem_fnstd::bind之间进行更好的比较。在那里,对于指针到会员的特定用例,如果您要做的就是通过所有参数,mem_fn的详细说法就会少得多。给定这种简单类型:

struct A { 
    int x;
    int getX() { return x; }
    int add(int y) { return x+y; }
};
A a{2};

您将如何制作一个刚刚在给定的A上调用getX()的函数?

auto get1 = std::mem_fn(&A::getX);
auto get2 = std::bind(&A::getX, _1);
get1(a); // yields 2
get2(a); // same

并提取add的其他参数?

auto add1 = std::mem_fn(&A::add);
auto add2 = std::bind(&A::add, _1, _2);
add1(a, 5); // yields 7
add2(a, 5); // same

因此,在这种情况下,mem_fn更简洁。但是,如果我们想绑定特定的参数,请在给定的A上呼叫add(5),您只能使用bind

来执行此操作。
auto add_5 = std::bind(&A::add, _1, 5);
add_5(a); // yields 7 

最终,functionmem_fn之间没有比较,但是有时比mem_fn更喜欢CC_20。

std::mem_fn返回的包装器非常轻巧;这是围绕成员指针的薄包装。

std::function使用类型擦除,这要重量级得多。