STD ::功能和std :: mem_fn有什么区别
What is the difference between std::function and std::mem_fn
我在找出两个函数包装器std::function
和std::mem_fn
之间的区别时遇到了麻烦。从描述来看,在我看来,std ::函数可以完成std::mem_fn
的所有功能。在哪种情况下,将在std::function
上使用std::mem_fn
?
您无法真正将std::function
与std::mem_fn
进行比较。前者是一个类模板,其类型是您指定的类型,后者是具有未指定返回类型的函数模板。实际上,您实际上并没有考虑到一个情况与另一个情况。
可以在mem_fn
和std::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
最终,function
和mem_fn
之间没有比较,但是有时比mem_fn
更喜欢CC_20。
std::mem_fn
返回的包装器非常轻巧;这是围绕成员指针的薄包装。
std::function
使用类型擦除,这要重量级得多。
相关文章:
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- int(c) 和 c-'0' 之间的区别。C++
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- C++ - "!pointer"和"pointer == nullptr"的区别?
- C++ 使用 assign 函数的字符串与直接使用 '=' 更改值的字符串之间的区别
- std::atomic和std::condition_variable wait,notify_*方法之间的区别
- 在 .h 文件中的类中声明静态变量和在.cpp文件中声明"global"变量有什么区别
- 我是C++编程的新手,这些代码之间有什么区别,我应该使用哪一个
- 在 const 函数中通过引用和指针返回之间的区别
- 我想知道长双倍和双倍之间的区别
- 返回常量对象引用 (getter) 和仅返回字符串有什么区别?
- 返回递归调用和仅递归调用的区别
- Qt:remove() 和 rmdir() 有什么区别
- 这 4 个 lambda 表达式之间有什么区别?
- 结构体 S { int align; } 之间的区别;(struct 关键字后的名称)和 struct { int al
- (double) 和 double() 之间的区别
- 将向量作为类>(值)<向量启动和向量<类>[值]有什么区别
- "double* grade"、"double *grade"和"double* fn()"有什么区别?
- "int f(int(fn)())"和"int f(int(*fn)())"的区别?
- 没有命名空间的"namespace::fn"和"::fn"有什么区别?