C++ std::function 到成员函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5154116/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
std::function to member function
提问by hidayat
#include <functional>
struct A
{
int func(int x, int y)
{
return x+y;
}
};
int main()
{
typedef std::function<int(int, int) > Funcp;
A a;
//Funcp func = std:::bind(&A::func, &a);
Funcp func = std::bind(&A::func, a, std::placeholders::_1);
return 0;
}
I am getting errors in both of the above bind functions:
我在上述两个绑定函数中都遇到错误:
error C2825: '_Fty': must be a class or namespace when followed by '::'
Where is the syntax error? I am using visual studio 2010
语法错误在哪里?我正在使用 Visual Studio 2010
回答by ltjax
Funcp func = std::bind(&A::func, &a, std::placeholders::_1, std::placeholders::_2);
Funcp func = std::bind(&A::func, &a, std::placeholders::_1, std::placeholders::_2);
回答by ap-osd
It took a while for me to figure out what's happening. So adding it here for the benefit of others, where an explanation would help. I've renamed some functions and variables for more clarity.
我花了一段时间才弄清楚发生了什么。因此,为了其他人的利益,将其添加到此处,解释会有所帮助。为了更清晰,我重命名了一些函数和变量。
#include <functional>
struct A
{
int MemberFunc(int x, int y)
{
return x+y;
}
};
int main()
{
typedef std::function<int(int, int) > OrdinaryFunc;
A a;
OrdinaryFunc ofunc = std::bind(&A::MemberFunc, a, std::placeholders::_1, std::placeholders::_2);
int z = ofunc(10, 20); // Invoke like an ordinary function
return 0;
}
Class member functions have an implicit/hidden parameter which points to the object (this
pointer). These member functions can be invoked only by providing an object, which makes it different from an ordinary function.
类成员函数具有指向对象(this
指针)的隐式/隐藏参数。这些成员函数只能通过提供一个对象来调用,这使得它不同于普通函数。
std::bind
can be used to "convert" a member function into an ordinary function. In the new function, the object is boundto the implicit/hidden parameter of the member function, and need not be passed when invoked. The unbound arguments are represented by the placeholders _1
, _2
and have to be passed when invoked.
std::bind
可用于将成员函数“转换”为普通函数。在新函数中,对象绑定到成员函数的隐式/隐藏参数,调用时不需要传递。未绑定的参数由占位符表示_1
,_2
并且必须在调用时传递。