gpt4 book ai didi

c++11 - C++0x 函数<>、绑定(bind)和成员

转载 作者:行者123 更新时间:2023-12-04 11:43:43 26 4
gpt4 key购买 nike

我试着关注 Bjarne Stroustups function的解释模板。我专门研究了 c 函数指针、仿函数、lambda 和成员函数指针的可互换性

给定定义:

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
}

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

我要绑定(bind) f到现有的 x实例成员函数,因此只有签名 float(int,int)离开了。

应该是什么行而不是
f = bind(g, &x,_2,_3);

...或者错误在哪里?

背景:

这里是使用 bind 的 Bjarnes 示例和 function带有成员函数:
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)

关于霍华德的建议下面我试过了:-) order of args in bind

最佳答案

f = bind(g, &x,_1,_2); // OK

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

关于c++11 - C++0x 函数<>、绑定(bind)和成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6169966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com