代码之家  ›  专栏  ›  技术社区  ›  jyoung

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

  •  1
  • jyoung  · 技术社区  · 15 年前

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

    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); };
        } 
    };
    
    2 回复  |  直到 15 年前
        1
  •  1
  •   David Rodríguez - dribeas    15 年前

    你试过了吗? 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;
    }
    

    正如你所看到的,在这两种情况下,你都在做同样的事情。我使用了私有和公共方法作为例子来证明 绑定 ,成员方法访问级别在绑定位置检查,而不是在调用位置检查。所以即使 MemberFn 在类中是私有的,可以通过绑定函数调用它。如果成员是公共的,则实际上可以从类外部绑定。

        2
  •  0
  •   Puppy    15 年前

    也许可以用boost::lambda生成一些内容,但实际上,我建议不要这样做,除非您发现使用尾随返回类型比显式typedef更容易。另外,据我所知,当您将此捕获为特殊情况时,lambda会变成成员lambda,就像它一样,您不需要显式this->。