std::function使用指南

std::function本质就是函数指针,通过std::bind和std::placeholders还可以改变函数入参个数。

  • 例子一
#include <iostream>
#include <functional>

void func(int a, int b, int c) {
    std::cout << a - b - c << std::endl;
}

int main() {
    std::function<void(int)> fn1                        // fn1 points to any function, which prototype as void (int);
        = std::bind(func, std::placeholders::_1, 2, 3); // fn1(x) = func(x,2,3)
    fn1(10);                                            // output 5

    return 0;
}

其中,

std::function<void(int)> fn1

也可以简单的写成:

auto fn1

编译器会通过等号后面的内容,把auto推导为std::function<void(int)>.

  • 例子二
#include <iostream>
#include <functional>

void func(int a, int b, int c) {
    std::cout << a - b - c << std::endl;
}

int main() {
    using namespace std::placeholders;
    auto fn1 = std::bind(func, _2, 2, _1);
    auto fn2 = std::bind(func, _1, 2, _2);

    fn1(1, 13);
    fn2(1, 13);

    return 0;
}

请读者推测一下输出怎样?



















$ g++ a.cpp && ./a.out
10
-14

如果你都答对了,恭喜你,你已经了解了std::function基本原理了。

参考

https://www.geeksforgeeks.org/bind-function-placeholders-c/

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容