【发布时间】:2016-12-14 03:28:12
【问题描述】:
我依稀记得python允许类似的东西
def foo( x ):
....
f = foo( 5 )
在 c++ 中是否有可能,所以如果我有一个成员函数
class C {
void foo( int x ) { ... }
so that I can define a pointer or variable that would effectively point at foo( 5 )
我之所以要这样做是因为我有很多听众需要订阅回调并保留被调用的信息
class C {
map<int, ptrSender> m_sender;
void subscribe() {
for (const auto& p : m_sender) {
p .second->register( Callback( this, &C::onCall ) )
}
我的问题是 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 ); }
....
我希望我可以将一些东西传递到寄存器中,它会返回一个带有预设参数的调用。这可能吗?
编辑:我正在尝试使用 lambda 函数,但遇到以下问题
auto setCall= [this]( int v ) { &C::onCall( v ); }
给出编译错误
lvalue required as unary&opeand
这个
auto setCall= [this]( int v ) { C::onCall( v ); }
....
p.second->register( Callback( this, &setCall( p.first) ) ); /// <__ error now here
再次抱怨,现在在第二行
lvalue required as unary&operand
还有这个
auto setCall= [this]( int v ) { C::onCall( v ); }
....
p.second->register( Callback( this, setCall( p.first) ) ); /// <__ error now here
抱怨无效使用 void 表达式,但我认为我必须传入一个引用才能使注册函数快乐
回调似乎被定义为
# define CallBack(obj,func) ProfiledBasicCallBack(obj,fastdelegate::FastDelegate0<void>(obj,func),#func)
【问题讨论】:
-
看起来你想使用绑定:stackoverflow.com/questions/6610046/…
-
那个绑定看起来很有希望,让我试试
-
如果你更喜欢 lambda 而不是 bind。
-
你的
register函数的参数类型是什么?具体是第二个参数。
标签: c++ function-pointers