1. 包装器概念与设计初衷
C++11引入的包装器(Wrapper)本质上是一种类型安全的函数封装机制。它解决了传统函数指针在面向对象编程中的类型安全问题,同时统一了各种可调用对象的调用方式。在实际工程中,我们经常需要处理以下几种可调用实体:
- 普通函数
- 类成员函数
- 函数对象(仿函数)
- lambda表达式
在C++11之前,这些可调用实体的类型系统各不相同,导致模板代码需要为每种情况编写特化版本。包装器的核心价值在于提供统一的类型擦除机制,使得这些不同类型的可调用实体能够以相同的方式被存储和调用。
关键洞察:包装器不是简单的语法糖,而是C++类型系统演进的重要里程碑。它使得"函数作为一等公民"的理念在静态类型语言中得以实现。
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 核心包装器类型详解
2.1 std::function 通用函数包装器
std::function是包装器家族中最通用的类型,其声明形式为:
cpp复制std::function<返回值类型(参数类型列表)>
典型使用场景示例:
cpp复制#include <functional>
#include <iostream>
void print_num(int i) {
std::cout << "Number: " << i << '\n';
}
struct PrintNum {
void operator()(int i) const {
std::cout << "Number: " << i << '\n';
}
};
int main() {
// 包装自由函数
std::function<void(int)> f1 = print_num;
f1(42);
// 包装函数对象
std::function<void(int)> f2 = PrintNum();
f2(43);
// 包装lambda
std::function<void(int)> f3 = [](int i){
std::cout << "Number: " << i << '\n';
};
f3(44);
}
2.2 std::bind 参数绑定器
std::bind实现了部分函数应用(Partial Function Application),允许我们:
- 重新排列参数顺序
- 绑定固定参数值
- 将成员函数绑定到特定对象实例
技术实现要点:
cpp复制#include <functional>
#include <iostream>
void print_sum(int a, int b) {
std::cout << a + b << '\n';
}
struct Foo {
void print_sum(int a, int b) const {
std::cout << a + b << '\n';
}
int data = 10;
};
int main() {
// 绑定自由函数
auto f1 = std::bind(print_sum, 1, std::placeholders::_1);
f1(5); // 输出6
// 绑定成员函数
Foo foo;
auto f2 = std::bind(&Foo::print_sum, &foo,
std::placeholders::_1, std::placeholders::_2);
f2(5, 10); // 输出15
// 绑定数据成员
auto f3 = std::bind(&Foo::data, std::placeholders::_1);
std::cout << f3(foo) << '\n'; // 输出10
}
2.3 std::mem_fn 成员函数包装器
std::mem_fn专门用于包装成员函数指针,相比std::bind语法更简洁:
cpp复制#include <functional>
#include <vector>
struct Foo {
void display() const { std::cout << "Foo\n"; }
int value() const { return 42; }
};
int main() {
std::vector<Foo> v(3);
// 传统成员函数指针调用
void (Foo::*pDisplay)() const = &Foo::display;
(v[0].*pDisplay)();
// 使用mem_fn
auto display = std::mem_fn(&Foo::display);
std::for_each(v.begin(), v.end(), display);
auto value = std::mem_fn(&Foo::value);
int total = 0;
for (const auto& item : v) {
total += value(item);
}
std::cout << total << '\n'; /
