bind函数返回(bind函数的用法和参数)

http://www.itjxue.com  2023-01-27 07:44  来源:未知  点击次数: 

c++11里面的bind函数是什么鬼,看不懂,请高手指教

std::bind

简单调用(1)

template?class?Fn,?class...?Args

?/*?未指定?*/?bind?(Fn?fn,?Args...?args);

跟上返回值(2)

template?class?Ret,?class?Fn,?class...?Args

?/*?未指定?*/?bind?(Fn?fn,?Args...?args);

绑定(Bind)函数与参数的作用,

返回一个基于fn的函数对象,但是已经提前绑定了调用需要的参数。

调用这个函数对象相当于调用用绑定的参数调用fn。

下面给你一个使用例子吧:

//?bind?用例

#include?iostream

#include?functional

//?自定义的一个函数

double?my_divide?(double?x,?double?y)?{return?x/y;}

//?自定义的一个结构体

struct?MyPair?{

??double?a,b;

??double?multiply()?{return?a*b;}

};

int?main?()?{

??//?这个using是为了使用?_1,?_2,?_3,...

??using?namespace?std::placeholders;

??//?捆绑函数:

??auto?fn_five?=?std::bind?(my_divide,10,2);?//?返回?10/2

??std::cout??fn_five()??'\n';?//?输出?5

??auto?fn_half?=?std::bind?(my_divide,_1,2);?//?返回?x/2

??std::cout??fn_half(10)??'\n';?//?输出?5

??auto?fn_invert?=?std::bind?(my_divide,_2,_1);?//?返回?y/x

??std::cout??fn_invert(10,2)??'\n';?//?输出?0.2

??auto?fn_rounding?=?std::bindint?(my_divide,_1,_2);?//?返回?int(x/y)

??std::cout??fn_rounding(10,3)??'\n';?//?输出?3

??MyPair?ten_two?{10,2};

??//?捆绑成员函数:

??auto?bound_member_fn?=?std::bind?(MyPair::multiply,_1);?//?返回?x.multiply()

??std::cout??bound_member_fn(ten_two)??'\n';?//?输出?20

??auto?bound_member_data?=?std::bind?(MyPair::a,ten_two);?//?返回?ten_two.a

??std::cout??bound_member_data()??'\n';?//?输出?10

??return?0;

}

运行结果:

5

5

0.2

3

20

10

socket编程中。bind()函数返回errno=99,何故?

你所谓的bind阻塞,是指程序运行到bind函数这里卡住了?确定是bind阻塞,而不是后面的某语句阻塞?

另外,你socket开启了REUSE_ADDR选项了没有?

boost:bind的返回值类型是什么额解决方法

bind的返回类型是std::function模板对应的实例,是一个函数对象。

(责任编辑:IT教学网)

更多

推荐思科认证文章