如何结合 std::bind()、可变参数模板和完美转发?

我想通过第三方函数调用另一个方法;但两者都使用可变参数模板.例如:

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&&’

我尝试使用 lambda,但 也许 GCC 4.8 还没有处理语法;这是我尝试过的:

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)...); };

我收到以下错误:

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

据我所知,编译器想要实例化 invoke_impl 类型为 int&&,而我认为使用 &&> 在这种情况下将保留实际参数类型.

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.

我做错了什么?谢谢,

推荐答案

Binding to &foo::invoke_impl<Args...> 将创建一个带有 的绑定函数Args&& 参数,表示右值.问题是传递的参数将是一个左值,因为参数被存储为某个内部类的成员函数.

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.

要修复,通过将 &foo::invoke_impl<Args...> 更改为 &foo::invoke_impl<Args&...> 来利用引用折叠规则. 所以成员函数将采用左值.

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)...);

这是一个演示.

相关文章