chr*_*ise 1 c++ function-pointers
我隐约记得python允许类似的东西
def foo( x ):
....
f = foo( 5 )
Run Code Online (Sandbox Code Playgroud)
在c ++中是这样的,所以如果我有一个成员函数
class C {
void foo( int x ) { ... }
so that I can define a pointer or variable that would effectively point at foo( 5 )
Run Code Online (Sandbox Code Playgroud)
我想这样做的原因是因为我有很多听众需要订阅回调并保留被调用的信息
class C {
map<int, ptrSender> m_sender;
void subscribe() {
for (const auto& p : m_sender) {
p .second->register( Callback( this, &C::onCall ) )
}
Run Code Online (Sandbox Code Playgroud)
我的问题是onCall没有返回哪个发送回叫,但我需要这些信息.所以,而不是做这样的事情
void subscribe() {
m_sender[0]->register( Callback( this, onCall_0 ) );
m_sender[1]->register( Callback( this, onCall_1 ) );
....
void onCall( int sender_id ) { ... }
void onCall_0() { onCall( 0 ); }
void onCall_1() { onCall( 1 ); }
....
Run Code Online (Sandbox Code Playgroud)
我希望我可以将一些内容传递给寄存器,该寄存器将返回带有预设参数的调用.这可能吗?
编辑:我正在尝试使用lambda函数,但我遇到了以下问题
auto setCall= [this]( int v ) { &C::onCall( v ); }
Run Code Online (Sandbox Code Playgroud)
给出了编译错误
lvalue required as unary&opeand
Run Code Online (Sandbox Code Playgroud)
这个
auto setCall= [this]( int v ) { C::onCall( v ); }
....
p.second->register( Callback( this, &setCall( p.first) ) ); /// <__ error now here
Run Code Online (Sandbox Code Playgroud)
再次抱怨,现在在第二行
lvalue required as unary&operand
Run Code Online (Sandbox Code Playgroud)
还有这个
auto setCall= [this]( int v ) { C::onCall( v ); }
....
p.second->register( Callback( this, setCall( p.first) ) ); /// <__ error now here
Run Code Online (Sandbox Code Playgroud)
抱怨无效使用void表达式,但我想我必须传入一个引用来使寄存器函数满意
回调似乎被定义为
# define CallBack(obj,func) ProfiledBasicCallBack(obj,fastdelegate::FastDelegate0<void>(obj,func),#func)
Run Code Online (Sandbox Code Playgroud)
是的,你可以使用std :: bind.用法示例:http://ideone.com/akoWbA.
void foo( int x ) { cout << x << endl; }
auto x = std::bind(foo, 5);
x();
Run Code Online (Sandbox Code Playgroud)
但是,使用现代C++,您应该使用lambda.像这样:
void foo( int x ) { cout << x << endl; }
auto x = []() { foo(5); };
x();
Run Code Online (Sandbox Code Playgroud)
请注意,此foo函数在此示例中位于C类之外.如果你想把它包含在里面,那么使用std :: bind你需要传递你想要调用的对象的实例,例如
C c;
auto x = std::bind(&C::foo, &c, 5);
x();
Run Code Online (Sandbox Code Playgroud)
或与lambdas:
C c;
auto x = [&c]() { c.foo(5); };
x();
Run Code Online (Sandbox Code Playgroud)