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

piwi picture piwi · Aug 22, 2013 · Viewed 8.1k times · Source

I want to invoke a method from another, through a third-party function; but both use variadic templates. For example:

void third_party(int n, std::function<void(int)> f)
{
  f(n);
}

struct foo
{
  template <typename... Args>
  void invoke(int n, Args&&... args)
  {
    auto bound = std::bind(&foo::invoke_impl<Args...>, this,
                           std::placeholders::_1, std::forward<Args>(args)...);

    third_party(n, bound);
  }

  template <typename... Args>
  void invoke_impl(int, Args&&...)
  {
  }
};

foo f;
f.invoke(1, 2);

Problem is, I get a compilation error:

/usr/include/c++/4.7/functional:1206:35: error: cannot bind ‘int’ lvalue to ‘int&&’

I tried using a lambda, but maybe GCC 4.8 does not handle the syntax yet; here is what I tried:

auto bound = [this, &args...] (int k) { invoke_impl(k, std::foward<Args>(args)...); };

I get the following error:

error: expected ‘,’ before ‘...’ token
error: expected identifier before ‘...’ token
error: parameter packs not expanded with ‘...’:
note:         ‘args’

From what I understand, the compiler wants to instantiate invoke_impl with type int&&, while I thought that using && in this case would preserve the actual argument type.

What am I doing wrong? Thanks,

Answer

0x499602D2 picture 0x499602D2 · Aug 22, 2013

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.