Combining a non-static method in std :: function with the "this" parameter using as little code as possible

Here is what I am trying to do:

template <typename ...Arguments>    
class CSignal
{
public:
    void connect(std::function<void(Arguments...)> target)
    {
        m_connections.emplace_back(target);
    }

private:
    mutable std::vector<std::function<void(Arguments...)>> m_connections;
};

And connectworks great for static methods or global functions. Now, if I want to pass a member method? This seems to be my only option:

struct MyStruct
{
    void print(float a, int b)
    {
        std::cout << a << " " << b << std::endl;
    }
} st;

signal.connect(std::bind(&MyStruct::print, &st, std::placeholders::_1, std::placeholders::_2));

It would suit me if I didn't have to specify placeholders, which are rather bulky. So I'm trying a different approach. I add a new overload connectfor member methods:

template <class T, typename Method>
void connect(const T* target, Method method)
{
    m_connections.emplace_back([=](Arguments... args){target->*method(std::forward<Arguments>(args)...);});
}

And then:

 signal.connect(&st, &MyStruct::print);

But now I get a compilation error:

the term does not evaluate a function that takes 2 arguments

at

m_connections.emplace_back([=](Arguments... args){target->*method(std::forward<Arguments>(args)...);});

What is the problem? And is there a way to do this without declaring a second overload connector using std::bindwith placeholders?

. S. connect, , , Method - T Method ?

+4
1
  • - ->* :

    (target->*method)(std::forward<Arguments>(args)...);
    ^               ^
    
  • - const ( const T*) - const :

    void print(float a, int b) const
                               ^^^^^
    
  • , - T ?

    template <class T>
    void connect(const T* target, void (T::*method)(Arguments...) const)
    
+6

Source: https://habr.com/ru/post/1568441/


All Articles