std :: function和std :: mem_fn之间的区别是什么 [英] What is the difference between std::function and std::mem_fn

查看:237
本文介绍了std :: function和std :: mem_fn之间的区别是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法弄清楚两个函数包装器std :: function和std :: mem_fn之间的区别。从描述,在我看来,std :: function做一切的std :: mem_fn做和更多。在哪个实例中会使用std :: mem_fn over std :: function?

I am having trouble figuring out the difference between the two function wrappers std::function and std::mem_fn. From the description, it seems to me that std::function does everything std::mem_fn does and more. In which instance would one use std::mem_fn over std::function?

推荐答案

$ c> std :: function 与 std :: mem_fn 。前者是一个类模板,你指定的类型,后者是一个具有未指定返回类型的函数模板。真的没有一种情况,你实际上认为一个对另一个。

You can't really compare std::function with std::mem_fn. The former is a class template whose type you specify, and the latter is a function template with unspecified return type. There really isn't a situation in which you'd actually consider one versus the other.

更好的比较可能在 mem_fn std :: bind 。在这里,对于指向成员指针的使用情况, mem_fn 会减少很多冗长,如果你想做的是传递所有的参数。给定这个简单的类型:

A better comparison might be between mem_fn and std::bind. There, for the specific use-case of a pointer-to-member, mem_fn is going to a lot less verbose if all you want to do is pass-through all the arguments. Given this simple type:

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

A a{2};

如何创建一个只是调用 getX c $ c>对于给定的 A

How would you make a functor that just calls getX() on a given A?

auto get1 = std::mem_fn(&A::getX);
auto get2 = std::bind(&A::getX, _1);

get1(a); // yields 2
get2(a); // same

并为添加一个额外的参数

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

So mem_fn is more concise in this case. However, if we wanted to bind a specific argument, say call add(5) on a given A, you can only do that with bind:

auto add_5 = std::bind(&A::add, _1, 5);
add_5(a); // yields 7 

最终,函数 mem_fn ,但有时候喜欢 mem_fn bind

Ultimately, no comparison between function and mem_fn, but there are times to prefer mem_fn to bind.

这篇关于std :: function和std :: mem_fn之间的区别是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆