【问题标题】:Is there a simple way to forward to a member function with a matching function signature?有没有一种简单的方法可以转发到具有匹配函数签名的成员函数?
【发布时间】:2011-03-08 01:12:52
【问题描述】:

有没有一种简单的方法可以转发到具有匹配函数签名的成员函数?

typedef std::tr1::function<int(int,int,int,int)> TheFn;
class C
{
    int MemberFn(int,int,int,int) { return 0; }

    TheFn getFn() { 
        //is there a simpler way to write the following line?
        return [this](int a,int b,int c,int d){ return this->MemberFn(a,b,c,d); };
    } 
};

【问题讨论】:

  • 也许您可以通过查看 std::mem_fun 的实现方式获得一些见解?
  • 我认为你需要澄清你在这里真正想要完成的事情。我不认为你所问的(本身)是可能的,但它足够接近,我怀疑一旦我们知道它是什么,潜在的问题仍然可以解决。
  • 在我的应用程序中,我有数百个使用可选设置器和获取器初始化的“智能通信块”。大多数情况下,这些只是转发给在特定对象上具有相同签名的成员函数。我希望有像 MagicBind(this, &MemberFn) 这样的东西。我只是想减少代码噪音。

标签: c++ visual-c++ c++11


【解决方案1】:

你试过bind吗?

// C++0x update
struct test {
   void f( int, int, int, int );
};
int main()
{
   std::function<void (int,int,int,int)> fn;
   test t;
   fn = std::bind( &t::f, &t, 
           std::placeholders::_1, 
           std::placeholders::_2, 
           std::placeholders::_3, 
           std::placeholders::_4 );
   fn( 1, 2, 3, 4 ); // t.f( 1, 2, 3, 4 )
}

我已经保留了所有元素的完整限定,但是std::placeholders 应用了这么多次并没有真正提高可读性...我想using std::placeholders 一点也不会受到伤害:

using std::placeholders;
fn = std::bind( &t::f, &t, _1, _2, _3, _4 );

编辑:使其更接近问题代码,以便更清楚地表明它与原始代码具有完全相同的功能:

typedef std::function<int(int,int,int,int)> TheFn;
class C {
   int MemberFn( int, int, int, int ) { return 0; }
public:
   int MemberFn2(int,int,int,int) { return 2; }
   TheFn getFn() {
      using std::placeholders;
      return std::bind( &C::MemberFn, this, _1, _2, _3, _4 );
   }
};
int main() {
   C instance;
   TheFn fn1 = instance.getFn();
   std::cout << fn1( 1, 2, 3, 4 ) << std::endl; // 0

   using std::placeholders;
   TheFn fn2 = std::bind( &C::MemberFn2, &instance, _1, _2, _3, _4 );
   std::cout << fn2( 1, 2, 3, 4 ) << std::endl;
}

正如您在这两种情况下看到的那样,您正在做同样的事情。我在例子中使用了私有和公有方法来说明当你bind时,成员方法访问级别是在绑定的地方检查的,而不是在调用的地方。因此,即使MemberFn 在类中是私有的,您也可以通过绑定函子调用它。如果成员是公共的,您实际上可以从类外部绑定。

【讨论】:

    【解决方案2】:

    也许可以用 Boost::Lambda 做点什么,但实际上,我不建议这样做,除了你可能会发现使用尾随返回类型比显式 typedef 更容易。此外,据我所知,当您捕获 this 时,作为一种特殊情况,lambda 会成为成员 lambda,并且您不需要显式 this->。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-15
      • 2011-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-27
      • 1970-01-01
      相关资源
      最近更新 更多