【问题标题】:C++0x function<>, bind and membersC++0x 函数<>、绑定和成员
【发布时间】:2011-05-29 19:38:05
【问题描述】:

我尝试按照Bjarne Stroustupsfunction 模板的解释。我专门研究了 c-function-pointersfunctorslambdasmember-function-pointers 的可互换性

根据定义:

struct IntDiv { // functor
  float operator()(int x, int y) const
    { return ((float)x)/y; }
};

// function pointer
float cfunc(int x, int y) { return (float)x+y; }

struct X { // member function
  float mem(int x, int y) const { return ...; }
};
using namespace placeholders; // _1, _2, ...

我想尽一切可能分配给function&lt;float(int,int)&gt;

int main() {
  // declare function object
  function<float (int x, int y)> f;
  //== functor ==
  f = IntDiv{};  // OK
  //== lambda ==
  f = [](int x,int y)->float { return ((float)y)/x; }; // OK
  //== funcp ==
  f = &cfunc; // OK

  // derived from bjarnes faq:
  function<float(X*,int,int)> g; // extra argument 'this'
  g = &X::mem; // set to memer function      
  X x{}; // member function calls need a 'this'
  cout << g(&x, 7,8); // x->mem(7,8), OK.

  //== member function ==
  f = bind(g, &x,_2,_3); // ERROR
}

最后一行给出了一个典型的不可读的编译器模板错误。 叹息

我想将f 绑定到现有的x 实例成员函数,这样就只剩下签名float(int,int)

应该用什么线代替

f = bind(g, &x,_2,_3);

...或者还有什么错误?


背景:

这里是使用 bindfunction 与成员函数的 Bjarnes 示例:

struct X {
    int foo(int);
};
function<int (X*, int)> f;
f = &X::foo;        // pointer to member
X x;
int v = f(&x, 5);   // call X::foo() for x with 5
function<int (int)> ff = std::bind(f,&x,_1)

认为 bind是这样使用的:未分配的地方得到placeholders,其余的填入@​​987654336@。那么_1 nut 应该得到this 吗?因此最后一行是:

function<int (int)> ff = std::bind(f,&x,_2)

关于霍华德的建议,我试过了 :-)

【问题讨论】:

    标签: c++11 bind functional-programming member-function-pointers


    【解决方案1】:
    f = bind(g, &x,_1,_2); // OK
    

    占位符是指返回的绑定对象中的参数位置。不要索引g的参数。

    【讨论】:

    • 哦,太棒了,直到现在我都错过了。我想我需要为此画图,因为当我需要自己解释时。
    • 如果你知道如何把那幅画发回来,那就太好了!我相信它会帮助很多人! :-)
    猜你喜欢
    • 2011-10-15
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多