Search code examples
c++std-function

How can I pass a method of an object's class as std::function?


I have a function that needs to get std::function-type parameter. I also have an abstract-type pointer to an object. Is it possible to pass the method using only an object?

The function signature:

void foo(std::function<bool(int i)>);

The classes sample:

class IBase // interface
{
public:
    virtual bool sampleMethod(int i) = 0;
};

class Child1 : public IBase // one of the classes that inherit from IBase
{
public:
    bool sampleMethod(int i) override;
};

So there is this pointer to an object of one of the Child classes:

std::unique_ptr<IBase> ptr;

And I want to use it to pass the sampleMethod as a parameter of foo. Is there any way to do it using std or boost?


Solution

  • You can do this with std::bind and a placeholder:

    foo (std::bind (&IBase::sampleMethod, ptr.get (), std::placeholders::_1));
    

    You can also use a lambda which captures ptr:

    foo ([&ptr] (int i) { return ptr->sampleMethod (i); });
    

    In either case, as Yakk - Adam Nevraumont says, make sure that ptr outlives any references made to it, or copies made of it, in foo.

    Live demo