Specifying a member function as a callback in C ++ 11

I have the following:

typedef std::function<bool (const std::string&)> SomethingCoolCb;

class ClassA
{
public:
    void OnSomethingCool(const SomethingCoolCb& cb)
    {
        _cb = cb;
    }

private:
    SomethingCoolCb _cb;
};

class ClassB
{
public:
    ClassB();
    bool Juggle(const std::string& arg);

private:
    ClassA _obj;
};

and I want to specify the class function ClassB :: Juggle () as a callback to ClassB :: _ obj. Would there be a proper way to do this in C ++ 11 (in the ClassB constructor):

ClassB::ClassB()
{
    _obj.OnDoSomethingCool(
        [&](const std::string& arg) -> bool
        {
            return Juggle(arg);
        });
}

From what I understand, the compiler will make the std :: function object from the above lambda code. Therefore, when the callback call is called, it calls the std :: function :: operator () element, and then it will call ClassB :: Juggle () instead of calling the ClassB :: Juggle () class. If I'm not mistaken about what is happening under the covers, everything seems a little ineffective. Is there a better way?

+5
source share
1 answer

std::function, . .

- , std::mem_fn, bind , .

:

#include <string>
#include <functional>

template<typename F>
class ClassA
{
public:
    ClassA(F f) : _cb(f) {}

private:
    F _cb;
};

class ClassB
{
public:
    ClassB() 
  : _obj(std::bind(&ClassB::Juggle, this, 
                   std::placeholders::_1)) 
  {}
  bool Juggle(const std::string& arg) {return true;}
private:
    ClassA<decltype(std::bind(
                      std::declval<bool (ClassB::*)(const std::string&)>()
                      , std::declval<ClassB*>()
                      , std::placeholders::_1
                      ) ) > _obj;
};

int main()
{
  ClassB b;
  return 0;
}

, .

+6

All Articles