我有一个带有可变数量参数的成员函数,存储在a中std::function,我希望绑定实例并获得一个独立的函数对象.
template <class T, class R, class... Args>
void connect(const T& t, std::function<R(const T&, Args...)> f) {
std::function<R(Args...)> = /* bind the instance c into the function? */
}
// ...
Class c;
connect(c, &Class::foo);
Run Code Online (Sandbox Code Playgroud)
对于我使用的固定数量的参数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);
Run Code Online (Sandbox Code Playgroud)
问题是,我收到编译错误:
/usr/include/c++/4.7/functional:1206:35: error: cannot bind ‘int’ lvalue to ‘int&&’
Run Code Online (Sandbox Code Playgroud)
我尝试使用lambda,但也许 GCC 4.8还没有处理语法; 这是我试过的:
auto bound = [this, &args...] (int k) { invoke_impl(k, std::foward<Args>(args)...); };
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
error: expected ‘,’ before ‘...’ token
error: expected identifier …Run Code Online (Sandbox Code Playgroud)