【发布时间】:2011-05-29 19:38:05
【问题描述】:
我尝试按照Bjarne Stroustups 对function 模板的解释。我专门研究了 c-function-pointers、functors、lambdas 和 member-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<float(int,int)>:
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);
...或者还有什么错误?
背景:
这里是使用 bind 和 function 与成员函数的 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