【问题标题】:binding member functions in a variadic fashion以可变方式绑定成员函数
【发布时间】:2012-08-07 19:48:12
【问题描述】:

我有一个参数个数不定的成员函数,存储在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);

对于固定数量的参数,我会使用std::bind,但我不知道如何为可变参数执行此操作。

【问题讨论】:

  • 你到底是怎么得到Args...的?
  • 好的,我写的代码不同,希望这样更容易理解。
  • 是的。并使解决方案相当容易。 :)
  • @Xeo 这就是我喜欢听到的:D

标签: c++ templates c++11 variadic-templates std-function


【解决方案1】:

解决方案非常很简单,因为您已经拥有大量参数和一切:

template <class T, class R, class... Args>
void connect(const T& t, std::function<R(const T&, Args...)> f) {
  // or capture 't' by-value
  std::function<R(Args...)> fun = [&t,f](Args... args){ f(t,args...); };
  // ...
}

Live example.

【讨论】:

  • 这将在调用堆栈上添加一个额外的层,即我必须添加一些std::forward 魔法,这样就没有副作用,对吧?
  • @lucas:即使是巧妙的完美转发魔法也不会神奇地使通过std::function 的呼叫消失。 ;)
  • :P 但是不会复制超出需要的东西。
  • @lucas:如果您不想要不需要的副本,最好将 std::function 参数指定为引用。 ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-24
  • 2015-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多