How to combine std::bind(), variadic templates, and perfect forwarding?

Binding to &foo::invoke_impl<Args...> will create a bound function that takes an Args&& parameter, meaning an rvalue. The problem is that the parameter passed will be an lvalue because the argument is stored as a member function of some internal class.

To fix, utilize reference collapsing rules by changing &foo::invoke_impl<Args...> to &foo::invoke_impl<Args&...> so the member function will take an lvalue.

auto bound = std::bind(&foo::invoke_impl<Args&...>, this,
                       std::placeholders::_1, std::forward<Args>(args)...);

Here is a demo.

Leave a Comment