jeudi 7 novembre 2019

std::bind of member function with perfect forwarding

I have a requirement where I need to bind a member function and pass the arguments with perfect forwarding. This is part of a larger codebase. So, code might not seem relevant. But, I need to fix this in order to move forward.

I am aware of the lambda function solution and that works fine but I don't want to use that and understand why std::bind wrongly assumes that the argument passed to call the binded member function is an argument to that function

The exact compiler error is this:

:52:5: error: no matching function for call to object of type 'std::_Bind::*(std::_Placeholder<1>, B))(B)>' binder(&a);

But, the expected interpretation should be this: 'std::_Bind::*(B))(B)>'

#include <functional>

struct B{
    B(const B&) = delete;
    B(){}
    B(B &&b){}
};

template<typename Ret, typename... Args>
struct A{
    Ret send(Args... argx){
        return Ret();
    }
};

template<class Ret, class ...Args>
void bind_and_forward(Args... args)
{
    using ConnectionType = A<Ret, Args...>;
    auto binder = std::bind(&ConnectionType::send,std::placeholders::_1,std::forward<Args>(args)...);

    ConnectionType a; 
    binder(&a);
    //^---compiler error here
}

int main()
{
    B b;
    bind_and_forward<int,B>(std::move(b));
}

Aucun commentaire:

Enregistrer un commentaire