1

Following is my code:

class A {};
class Test
{
public:
    template <class TClass>
    Test(TClass* _objPointer, void(TClass::*_func)(A*))
    {
        mEventFunction = std::bind(_func, _objPointer);
    }
private:
    std::function<void(A*)> mEventFunction;
};

class Demo
{
public:
    void BindFunc()
    {
        mTest = new Test(this, &Demo::testFunc);
    }
    void testFunc(A*)
    {

    }
private:
    Test* mTest;
};

What I want to achieve is BindFunc() in Demo class. But this code run with lot of error message: error C2672: 'std::invoke': no matching overloaded function found ......

1
  • 3
    std::bind(_func, _objPointer, std::placeholders::_1). Commented Jan 12, 2017 at 12:48

1 Answer 1

5

You need to include a std::placeholders::_1 to account for the A* argument that you haven't bound yet:

#include <functional>

class A {};
class Test
{
public:
    template <class TClass>
    Test(TClass* _objPointer, void(TClass::*_func)(A*))
    {
        mEventFunction = std::bind(_func, _objPointer, std::placeholders::_1);
    }
private:
    std::function<void(A*)> mEventFunction;
};

class Demo
{
public:
    void BindFunc()
    {
        mTest = new Test(this, &Demo::testFunc);
    }
    void testFunc(A*)
    {

    }
private:
    Test* mTest;
};

Demo

I think it's a little clearer that you need some placeholder for A* if we used a lambda instead (Demo2):

template <class TClass>
Test(TClass* _objPointer, void(TClass::*_func)(A*))
{
    mEventFunction = [_objPointer, _func](A* _a){(_objPointer->*_func)(_a);};
}

Here the lambda accepts an argument for A*, which is what you wanted. I actually recommend the lambda approach over std::bind in nearly all use cases.

Sign up to request clarification or add additional context in comments.

2 Comments

Kudos for preferring the lambda to bind.
Thank you, this is a great answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.