如何组合std::bind()、可变模板和完美转发



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

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

问题是,我得到一个编译错误:

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

我尝试使用lambda,但可能GCC 4.8还不能处理语法;这是我试过的:

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’

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

我做错了什么?谢谢,

绑定到&foo::invoke_impl<Args...>将创建一个绑定函数,该函数接受Args&&参数,即右值。问题是,传递的参数将是左值,因为该参数存储为某个内部类的成员函数。

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

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

这是一个演示。

最新更新