自学内容网 自学内容网

C++ function & bind 学习笔记

文档声明:
以下资料均属于本人在学习过程中产出的学习笔记,如果错误或者遗漏之处,请多多指正。并且该文档在后期会随着学习的深入不断补充完善。感谢各位的参考查看。


笔记资料仅供学习交流使用,转载请标明出处,谢谢配合。
如果存在相关知识点的遗漏,可以在评论区留言,看到后将在第一时间更新。
作者:Aliven888

function

function 是一个通用的函数对象容器,可以存储任意可调用对象(函数、函数指针、成员函数、成员变量、lambda 表达式,任何 function 对象,比如一个类,定义了 operator() ),并提供了一致的接口来调用这些对象。通过 function ,可以将一个函数或函数对象作为参数传递给其他函数或存储在容器中,大大提高了灵活性。

格式:
std::function<return-type(param-type ...)> fun = funName;

  • return-type:函数返回值类型。
  • param-type … :函数参数(可以有多个,使用 逗号 分割)。
  • fun :定义的函数名称。
  • funName:目标函数名称。

bind

bind 是将函数和其参数进行绑定的工具,可以将一个函数和部分参数绑定在一起,生成一个新的函数对象,这个新的函数对象可以像原函数一样进行调用,但会自动填充绑定的参数。

格式:
bind(funName, param1, param2, ...);
bind(&class::funName, param1, param2, ...);

  • funName :函数名称。
  • class::funName :类成员函数名称(前面需要有 &)。
  • param :函数参数(可以有多个,使用 逗号 分割)。

Demo

#include <stdlib.h>
#include <functional>

std::int32_t funName(std::int32_t a, std::int32_t b) {
return a + b;
}

int main(int argc, char *argv[]) {
// 指向函数
    std::function<std::int32_t(std::int32_t, std::int32_t)> fun1 = funName;
    std::int32_t c = fun1(1, 2);
    printf("c = %d\n", c);

// 指向 lambda 表达式
    std::function<std::int32_t(std::int32_t, std::int32_t)> fun2 = 
        [](std::int32_t a, std::int32_t b) { return a + b; };
    std::int32_t d =  fun2(3, 4);
    printf("d = %d\n", d);

// bind 语法
    auto fun3 = std::bind(funName, 5, 6);
    std::int32_t e = fun3();
    printf("e = %d\n", e);
    return 0;
}

// 输出
c = 3
d = 7
e = 11

原文地址:https://blog.csdn.net/Aliven888/article/details/140214813

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!