12

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

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’

据我了解,编译器希望invoke_impl使用 type进行实例化int&&,而我认为&&在这种情况下使用会保留实际的参数类型。

我究竟做错了什么?谢谢,

4

1 回答 1

10

绑定到&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)...);

这是一个演示

于 2013-08-22T13:41:41.983 回答