(17)std::function

std::function 是 C++11 引入的通用可调用对象包装器,
它可以统一存储、传递和调用各种可调用对象(函数、lambda、成员函数、绑定表达式等),是实现回调、事件系统、函数式编程的核心工具。
1. 包装普通函数
double add(double a, double b) {
    return a + b;
}
std::function<double(double, double)> calc = add;
std::cout << calc(3.0, 4.0) << std::endl; // 输出 7
2. 包装 Lambda 表达式
std::function<int(int)> multiply = [factor](int x) {
        return x * factor;
};

std::cout << multiply(5) << std::endl; // 输出 10
3. 包装类的成员函数
class Calculator {
public:
    double multiply(double a, double b) {
        return a * b;
    }
};

Calculator calc;
// 绑定对象和成员函数
std::function<double(Calculator&, double, double)> func = &Calculator::multiply;

std::cout << func(calc, 3.0, 4.0) << std::endl; // 输出 12
4. 使用 std::bind

std::function<double(double, double)> bound_func = 
     std::bind(&Calculator::multiply, calc, std::placeholders::_1, std::placeholders::_2);

std::cout << bound_func(3.0, 4.0) << std::endl; // 输出 12
void greet(const std::string& name, const std::string& greeting) {
    std::cout << greeting << ", " << name << "!\n";
}
// 固定部分参数
auto say_hello = std::bind(greet, std::placeholders::_1, "Hello");
auto say_goodbye = std::bind(greet, std::placeholders::_1, "Goodbye");

std::function<void(std::string)> func = say_hello;
func("Alice");  // 输出: Hello, Alice!

func = say_goodbye;
func("Bob");    // 输出: Goodbye, Bob!
5. 作为函数参数(回调函数)
// 接受一个函数作为参数
void process_numbers(const std::vector<int>& nums, 
                     std::function<void(int)> callback) {

    for (int n : nums) {
        callback(n);
    }
}

std::vector<int> numbers = {1, 2, 3, 4, 5};

// 传递 lambda 作为回调
process_numbers(numbers, [](int n) {
            std::cout << "Processing: " << n << std::endl;
     });
6. 存储在容器中(函数表)
int square(int x) { return x * x; }
int cube(int x) { return x * x * x; }

std::vector<std::function<int(int)>> operations = {square, cube};
posted @ 2019-06-25 23:36  osbreak  阅读(309)  评论(0)    收藏  举报