我模糊地记得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)

最佳答案

是的,您可以使用std::bind。用法示例:http://ideone.com/akoWbA

void foo( int x ) { cout << x << endl; }
auto x = std::bind(foo, 5);
x();

但是,对于现代C++,您应该使用lambda。像这样:
void foo( int x ) { cout << x << endl; }
auto x = []() { foo(5); };
x();

请注意,在此示例中,此foo函数位于类C之外。如果您希望将其包含在内部,则需要使用std::bind传递您希望调用的对象的实例,例如
C c;
auto x = std::bind(&C::foo, &c, 5);
x();

或使用lambdas:
C c;
auto x = [&c]() { c.foo(5); };
x();

10-02 00:52
查看更多