std::bind和std::placeholder
std::bind()
https://cplusplus.com/reference/functional/bind/
examples:
double my_divide (double x, double y) {
return x/y;}
auto fn_five = std::bind (my_divide,10,2); // returns 10/2
Returns a function object based on fn, but with its arguments bound to args.
返回一个函数对象fn, 但他的参数是绑定到args的。
Each argument may either be bound to a value or be a placeholder:
每一个参数可以是一个值,也可以是一个占位符placeholder
- If bound to a value, calling the returned function object will always use that value as argument.
如果绑定到一个值,这个函数对象总是使用这个值作为参数 - If a placeholder, calling the returned function object forwards an argument passed to the call (the one whose order number is specified by the placeholder).
如果绑定到一个placeholder, 调用被返回函数对象的时候,即fn_five(),需要传入一个参数通过函数调用的形式,给这个placeholder
std::bind 是用来绑定函数调用的参数的。
它解决的需求是:有时候可能并不一定能够一次性获得调用某个函数的全部参数,通过这个函数,我们可以将部分调用参数提前绑定到函数身上成为一个新的对象,然后在参数齐全后,完成调用。
std::placeholder
https://cplusplus.com/reference/functional/placeholders/
placeholder是一个命名空间, 如果需要使用需要
using namespace placeholders;
namespace placeholders {
extern /* unspecified */ _1;
extern /* unspecified */ _2;
extern /* unspecified */ _3;
// ...
}
_1: Replaced