std::copyable_function
什么是 std::copyable_function
std::copyable_function 是 C++26 引入的多态函数包装器,定义在 <functional> 头文件中。它是 std::function 的改进版本——既支持拷贝,又支持在签名中指定 cv 限定、引用限定和 noexcept。
std::function 的 operator() 始终是 const 的,且不支持 noexcept 限定,这在某些场景中不够灵活。std::copyable_function 修复了这些设计上的不足,同时保留了可拷贝的特性。
#include <functional>
// std::function 的 operator() 总是 const
std::function<int(int)> f1;
// std::copyable_function 可以指定 const、noexcept 等限定
std::copyable_function<int(int) const noexcept> f2;三种函数包装器对比
| 特性 | std::function | std::move_only_function | std::copyable_function |
|---|---|---|---|
| 标准版本 | C++11 | C++23 | C++26 |
| 可拷贝 | 是 | 否 | 是 |
| 可移动 | 是 | 是 | 是 |
| cv/ref/noexcept 限定 | 不支持 | 支持 | 支持 |
| 调用空对象 | 抛异常 | 未定义行为 | 未定义行为 |
| target/target_type | 提供 | 不提供 | 不提供 |
| 目标要求可拷贝 | 是 | 否 | 是 |
基本示例
#include <iostream>
#include <functional>
#include <string>
#include <vector>
#include <algorithm>
// ============================
// 示例1:基本用法
// ============================
void basic_demo() {
// 包装 lambda
std::copyable_function<int(int, int)> add = [](int a, int b) {
return a + b;
};
std::cout << "3 + 4 = " << add(3, 4) << std::endl;
// 可以拷贝
auto add_copy = add;
std::cout << "拷贝后: " << add_copy(5, 6) << std::endl;
}
// ============================
// 示例2:const 限定
// ============================
void const_demo() {
// 签名带 const:通过 const 引用也能调用
std::copyable_function<int(int) const> func = [](int x) {
return x * 2;
};
// 可以通过 const 引用调用
const auto& ref = func;
std::cout << "const 调用: " << ref(21) << std::endl;
// 不带 const 的签名
int counter = 0;
std::copyable_function<int()> mutable_func = [counter]() mutable {
return ++counter;
};
std::cout << "mutable: " << mutable_func() << std::endl; // 1
std::cout << "mutable: " << mutable_func() << std::endl; // 2
}
// ============================
// 示例3:noexcept 限定
// ============================
void noexcept_demo() {
// 签名带 noexcept
std::copyable_function<int() const noexcept> safe = []() noexcept {
return 42;
};
std::cout << "noexcept: " << safe() << std::endl;
// 非 noexcept 的 lambda 不能赋值给 noexcept 签名
// std::copyable_function<int() noexcept> bad = [] { throw 1; }; // 编译错误
}
// ============================
// 示例4:与 std::function 对比——const 问题
// ============================
void const_issue_demo() {
int value = 0;
// std::function 的问题:operator() 是 const 的,但可以修改捕获的变量
std::function<void()> std_func = [&value]() { value++; };
const auto& const_ref = std_func;
const_ref(); // 通过 const 引用修改了 value——语义上不一致
std::cout << "std::function const 问题: value = " << value << std::endl;
// copyable_function 可以正确表达意图
// 如果签名是 const 的,就不能包装修改状态的 callable
// std::copyable_function<void() const> cf = [&value]() { value++; };
// 如果 lambda 修改捕获变量,需要 mutable,与 const 签名冲突
// 非 const 签名:明确允许修改
std::copyable_function<void()> cf = [&value]() { value++; };
cf();
std::cout << "copyable_function: value = " << value << std::endl;
}
// ============================
// 示例5:存储在容器中
// ============================
void container_demo() {
// 可以拷贝,因此可以存储在需要拷贝的容器中
std::vector<std::copyable_function<int(int) const>> transforms;
transforms.push_back([](int x) { return x * 2; });
transforms.push_back([](int x) { return x + 10; });
transforms.push_back([](int x) { return x * x; });
int value = 5;
for (const auto& f : transforms) {
std::cout << " " << value << " -> " << f(value) << std::endl;
}
// 拷贝整个容器
auto transforms_copy = transforms;
std::cout << "拷贝后仍可用: " << transforms_copy[0](3) << std::endl;
}
// ============================
// 示例6:回调系统
// ============================
class Observable {
std::vector<std::copyable_function<void(int) const>> observers_;
public:
void subscribe(std::copyable_function<void(int) const> callback) {
observers_.push_back(std::move(callback));
}
void notify(int value) const {
for (const auto& observer : observers_) {
observer(value);
}
}
// 可以拷贝整个 Observable(包括所有回调)
Observable copy() const {
Observable result;
result.observers_ = observers_; // 可以拷贝
return result;
}
};
void observer_demo() {
Observable subject;
subject.subscribe([](int v) {
std::cout << " 观察者A: " << v << std::endl;
});
subject.subscribe([](int v) {
std::cout << " 观察者B: " << (v * 2) << std::endl;
});
subject.notify(10);
// 拷贝 Observable
auto subject_copy = subject.copy();
std::cout << "拷贝后:" << std::endl;
subject_copy.notify(20);
}
// ============================
// 示例7:operator bool 检查
// ============================
void null_check_demo() {
std::copyable_function<void()> func;
std::cout << std::boolalpha;
std::cout << "空: " << (bool)func << std::endl; // false
func = [] { std::cout << "已赋值" << std::endl; };
std::cout << "赋值后: " << (bool)func << std::endl; // true
if (func) func();
func = nullptr;
std::cout << "清空后: " << (bool)func << std::endl; // false
}
int main() {
std::cout << "=== 基本用法 ===" << std::endl;
basic_demo();
std::cout << "\n=== const 限定 ===" << std::endl;
const_demo();
std::cout << "\n=== noexcept 限定 ===" << std::endl;
noexcept_demo();
std::cout << "\n=== const 问题对比 ===" << std::endl;
const_issue_demo();
std::cout << "\n=== 容器存储 ===" << std::endl;
container_demo();
std::cout << "\n=== 观察者模式 ===" << std::endl;
observer_demo();
std::cout << "\n=== 空检查 ===" << std::endl;
null_check_demo();
return 0;
}如何选择函数包装器
| 场景 | 推荐 |
|---|---|
| 需要拷贝 + cv/ref/noexcept 限定 | std::copyable_function |
| 只需要移动,不需要拷贝 | std::move_only_function |
| 旧代码兼容 | std::function |
| 不需要拥有所有权 | std::function_ref |
适用场景
- 回调系统中需要拷贝回调对象
- 需要精确控制 const/noexcept 语义的函数包装
- 观察者模式中需要拷贝整个观察者列表
- 替代 std::function 获得更好的类型安全
- 存储在需要可拷贝元素的容器中
常见问题
copyable_function 和 function 能互相转换吗?
不能直接转换。它们是不同的类型。但可以用相同的可调用对象分别构造。
调用空的 copyable_function 会怎样?
未定义行为。与 function 抛出 bad_function_call 不同,copyable_function 和 move_only_function 在空时调用是 UB。
为什么去掉了 target() 和 target_type()?
这些函数需要额外的类型擦除信息存储,增加了开销。实际使用中很少需要它们。去掉可以让实现更紧凑高效。
注意事项
- C++26 特性,编译器支持可能有限
- 调用空对象是未定义行为
- 不提供 target() 和 target_type()
- 被包装的目标必须是可拷贝的
- 签名中的限定影响 operator() 的调用方式
- 需要
<functional>头文件
总结
std::copyable_function 是 C++26 对 std::function 的改进版本。它保留了可拷贝的特性,同时增加了对 cv 限定、引用限定和 noexcept 的支持,修复了 std::function 中 operator() 始终为 const 的设计问题。与 std::move_only_function 相比,它额外要求被包装的目标可拷贝。在新代码中,如果需要可拷贝的函数包装器,推荐使用 std::copyable_function(当编译器支持时)代替 std::function。