我尝试按照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
,其余的填充在bind
. 那么,_1
坚果应该得到this
吗?因此最后一行是:
function<int (int)> ff = std::bind(f,&x,_2)
在下面的霍华德建议中,我尝试了它:-)