C++ <functional>
讲解 <functional> 函数对象模型、std::function 多态可调用封装、std::bind 与占位符参数绑定,以及算术/比较/逻辑标准仿函数与 C++17 std::not_fn 替代方案。
学完这一章,你能够
- 讲解 <functional> 函数对象模型、std::function 多态可调用封装、std::bind 与占位符参数绑定,以及算术/比较/逻辑标准仿函数与 C++17 std::not_fn 替代方案。
函数对象概念与标准内置仿函数
头文件 `<functional>` 围绕“函数对象(Function Object / Functor)”构建了丰富的可调用工具集。所谓函数对象,是指重载了函数调用运算符 `operator()` 的类实例,它既能像普通函数一样被调用,又能携带内部状态并作为对象传递给泛型算法或存储在容器中。使用前包含 `#include <functional>` 即可。
`<functional>` 提供了六大类常用组件:多态可调用封装器 `std::function`;参数绑定器 `std::bind` 及 `std::placeholders::_1` 等占位符;算术仿函数 `std::plus`、`std::minus`、`std::multiplies`、`std::divides`、`std::modulus`;比较仿函数 `std::equal_to`、`std::not_equal_to`、`std::greater`、`std::less`、`std::greater_equal`、`std::less_equal`;逻辑仿函数 `std::logical_and`、`std::logical_or`、`std::logical_not`;以及早期谓词否定适配器 `std::unary_negate`/`std::binary_negate`(注:该二者已于 C++17 标记弃用并在 C++20 移除,现代 C++17 代码应统一改用更通用的 `std::not_fn`)。
std::function、std::bind 与比较函数对象实践
`std::function<R(Args...)>` 借助类型擦除技术,可以统一存储、复制和调用签名兼容的普通函数、Lambda 表达式或自定义函数对象,常用于回调注册表与策略模式。若需避免堆分配与虚派发开销,在模板参数位置仍建议直接接受泛型可调用类型。
`std::bind` 可将部分实参预先固定到目标函数上,并通过 `std::placeholders::_1`、`_2` 指定调用时再传入的动态参数位置(甚至重排参数顺序)。例如 `auto bound_add = std::bind(add, 5, std::placeholders::_1);` 调用 `bound_add(10)` 即等价于 `add(5, 10)` 返回 `15`。在现代 C++ 中,Lambda 表达式通常比 `std::bind` 更直观且更利于编译器内联优化。
标准比较函数对象可直接配合 `std::sort` 等算法使用:既可以传入自定义比较函数 `compare`,也可直接传入 `std::less<int>()`(升序)或 `std::greater<int>()`(降序)。借助 `<functional>` 将“行为”一等公民化,能够写出高度解耦、可复用的泛型代码。本站已在离线 G++ C++17 容器实测 `std::function`、`std::bind`、全部算术/逻辑/比较仿函数及 `std::not_fn`。
实测 std::function、std::bind、算术/逻辑仿函数、std::not_fn 与排序比较器
#include <algorithm>
#include <cstdio>
#include <functional>
#include <iostream>
#include <string>
#include <vector>
namespace lab {
struct Case {
std::string name;
std::string expected_json;
std::string actual_json;
bool passed;
};
std::string esc(const std::string& s) {
std::string out = "\"";
for (unsigned char c : s) {
switch (c) {
case '\"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\b': out += "\\b"; break;
case '\f': out += "\\f"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (c < 0x20) {
char buf[8];
std::snprintf(buf, sizeof(buf), "\\u%04x", c);
out += buf;
} else {
out += static_cast<char>(c);
}
}
}
out += "\"";
return out;
}
std::string jbool(bool v) { return v ? "true" : "false"; }
void emit(const std::vector<Case>& cases) {
std::cout << "{\"runtime\": \"G++ C++17 (mstorsjo/llvm-mingw:20260616)\", \"cases\": [";
for (std::size_t i = 0; i < cases.size(); ++i) {
if (i) std::cout << ", ";
std::cout << "{\"name\": " << esc(cases[i].name)
<< ", \"expected\": " << cases[i].expected_json
<< ", \"actual\": " << cases[i].actual_json
<< ", \"passed\": " << jbool(cases[i].passed) << "}";
}
std::cout << "]}\n";
}
} // namespace lab
static std::string greet_fn() { return "Hello, World!"; }
struct ScaleFunctor {
int factor;
int operator()(int x) const { return x * factor; }
};
static int add_fn(int a, int b) { return a + b; }
static int sub_fn(int a, int b) { return a - b; }
static bool custom_asc(int a, int b) { return a < b; }
int main() {
std::vector<lab::Case> cases;
// Case 1: std::function wrapping free function, lambda, and functor
std::function<std::string()> f_fn = greet_fn;
std::function<std::string()> f_lam = []() -> std::string { return "Hello, Lambda!"; };
std::function<int(int)> f_obj = ScaleFunctor{3};
std::string act1 = f_fn() + "|" + f_lam() + "|" + std::to_string(f_obj(7));
std::string exp1 = "Hello, World!|Hello, Lambda!|21";
cases.push_back({
"functional_std_function_callables",
lab::esc(exp1),
lab::esc(act1),
act1 == exp1
});
// Case 2: std::bind with placeholders
auto bound_add = std::bind(add_fn, 5, std::placeholders::_1);
auto swapped_sub = std::bind(sub_fn, std::placeholders::_2, std::placeholders::_1);
std::string act2 = "add=" + std::to_string(bound_add(10)) + ";swap_sub=" + std::to_string(swapped_sub(3, 10));
std::string exp2 = "add=15;swap_sub=7";
cases.push_back({
"functional_std_bind_placeholders",
lab::esc(exp2),
lab::esc(act2),
act2 == exp2
});
// Case 3: arithmetic, logical functors and C++17 std::not_fn
int v_plus = std::plus<int>{}(7, 3);
int v_minus = std::minus<int>{}(7, 3);
int v_mul = std::multiplies<int>{}(7, 3);
int v_div = std::divides<int>{}(7, 3);
int v_mod = std::modulus<int>{}(7, 3);
bool l_and = std::logical_and<bool>{}(true, false);
bool l_or = std::logical_or<bool>{}(true, false);
bool l_not = std::logical_not<bool>{}(false);
auto is_even = [](int x) { return x % 2 == 0; };
auto is_odd = std::not_fn(is_even);
bool odd7 = is_odd(7);
std::string act3 = std::to_string(v_plus) + "," + std::to_string(v_minus) + ","
+ std::to_string(v_mul) + "," + std::to_string(v_div) + "," + std::to_string(v_mod)
+ ";and=" + std::to_string(l_and ? 1 : 0)
+ ";or=" + std::to_string(l_or ? 1 : 0)
+ ";not=" + std::to_string(l_not ? 1 : 0)
+ ";not_fn=" + std::to_string(odd7 ? 1 : 0);
std::string exp3 = "10,4,21,2,1;and=0;or=1;not=1;not_fn=1";
cases.push_back({
"functional_arithmetic_and_logical",
lab::esc(exp3),
lab::esc(act3),
act3 == exp3
});
// Case 4: comparison functors with std::sort
std::vector<int> v1 = {5, 3, 9, 1, 4};
std::vector<int> v2 = v1;
std::sort(v1.begin(), v1.end(), custom_asc);
std::sort(v2.begin(), v2.end(), std::less<int>{});
bool asc_eq = (v1 == v2);
std::sort(v2.begin(), v2.end(), std::greater<int>{});
std::string desc_s;
for (std::size_t i = 0; i < v2.size(); ++i) {
if (i) desc_s += ",";
desc_s += std::to_string(v2[i]);
}
bool cmp_ok = std::equal_to<int>{}(4, 4)
&& std::not_equal_to<int>{}(4, 5)
&& std::greater_equal<int>{}(5, 5)
&& std::less_equal<int>{}(3, 5);
std::string act4 = "asc_eq=" + std::to_string(asc_eq ? 1 : 0)
+ ";desc=" + desc_s
+ ";cmp=" + std::to_string(cmp_ok ? 1 : 0);
std::string exp4 = "asc_eq=1;desc=9,5,4,3,1;cmp=1";
cases.push_back({
"functional_comparators_with_sort",
lab::esc(exp4),
lab::esc(act4),
act4 == exp4
});
lab::emit(cases);
return 0;
}
- 确认 std::function 统一调用函数/Lambda/仿函数、std::bind 固定参数与重排参数、算术逻辑仿函数与 C++17 std::not_fn 正确,以及 std::less/std::greater 排序结果准确。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
当前源码 SHA256:fbd66e4c6633a789274e2c2180de82948d302f3b3d0703fac7a17d00de1fae1c
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,G++ 13.3.0 C++17 linux/amd64,--network none)。
ZIP SHA256:0ac6863f5b20f2b1d4085024c15ebffd7640a4e18ae99b12ff90f97ba05cbdb5
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 C++17 中为什么不建议继续使用 `std::unary_negate` / `std::binary_negate`,应当改用什么替代?
展开参考解答
二者依赖已移除的旧式可适配函数类型别名(如 `argument_type`),已在 C++17 弃用并在 C++20 删除;现代 C++17 应使用 `std::not_fn(pred)`(或直接编写取反 Lambda)。