std::any
什么是 std::any
std::any 是 C++17 在 <any> 头文件中引入的一个类,用来存储任意可拷贝构造类型的单个值。你可以把它理解为类型安全的 void*:它能持有任何类型的值,但和 void* 不同的是,它知道自己当前持有的是什么类型,访问时会进行类型检查。
std::any 使用了类型擦除(type erasure)技术:存入值时记住类型信息,取出时通过 std::any_cast 进行类型安全的转换。如果转换的目标类型和存储的实际类型不匹配,会抛出 std::bad_any_cast 异常(值转换版本)或返回 nullptr(指针转换版本)。
和 std::variant 不同,std::any 不需要在编译期列出所有可能的类型——它能存储任何满足 CopyConstructible 要求的类型。这种灵活性的代价是:对于大对象可能需要堆分配,运行时类型检查也比编译期类型检查要慢。
头文件与基本声明
#include <any>
std::any a; // 空,不持有任何值
std::any b = 42; // 持有 int
std::any c = std::string("hello"); // 持有 std::string
std::any d = 3.14; // 持有 double核心接口说明
| 成员/函数 | 说明 |
|---|---|
has_value() | 检查是否持有值 |
type() | 返回当前存储类型的 std::type_info |
reset() | 销毁存储的值,变为空 |
emplace<T>(args...) | 原地构造指定类型的值 |
std::any_cast<T>(a) | 值版本:类型匹配返回值的拷贝/移动,不匹配抛 bad_any_cast |
std::any_cast<T>(&a) | 指针版本:类型匹配返回指针,不匹配返回 nullptr |
std::make_any<T>(args...) | 创建并原地构造 any 对象 |
基本示例
#include <iostream>
#include <any>
#include <string>
#include <vector>
#include <typeinfo>
// ============================
// 示例1:基本存取操作
// ============================
void basic_usage() {
std::any a;
std::cout << "空? " << std::boolalpha << !a.has_value() << std::endl; // true
// 存入 int
a = 42;
std::cout << "类型: " << a.type().name() << std::endl;
std::cout << "值: " << std::any_cast<int>(a) << std::endl; // 42
// 存入 string(旧值自动销毁)
a = std::string("hello world");
std::cout << "值: " << std::any_cast<std::string>(a) << std::endl;
// 存入 double
a = 3.14;
std::cout << "值: " << std::any_cast<double>(a) << std::endl;
// reset 清空
a.reset();
std::cout << "reset 后有值? " << a.has_value() << std::endl; // false
}
// ============================
// 示例2:安全的类型转换
// ============================
void safe_cast_demo() {
std::any a = 42;
// 指针版本的 any_cast:不抛异常
if (auto* p = std::any_cast<int>(&a)) {
std::cout << "int 值: " << *p << std::endl;
}
if (auto* p = std::any_cast<double>(&a)) {
std::cout << "double 值: " << *p << std::endl;
} else {
std::cout << "不是 double 类型" << std::endl;
}
// 值版本的 any_cast:类型不匹配抛异常
try {
std::string s = std::any_cast<std::string>(a);
} catch (const std::bad_any_cast& e) {
std::cout << "类型转换失败: " << e.what() << std::endl;
}
}
// ============================
// 示例3:make_any 和 emplace
// ============================
void make_and_emplace_demo() {
// make_any:直接构造,避免临时对象
auto a = std::make_any<std::string>(5, 'A'); // "AAAAA"
std::cout << "make_any: " << std::any_cast<std::string>(a) << std::endl;
// emplace:原地替换为新类型新值
a.emplace<std::vector<int>>(std::initializer_list<int>{1, 2, 3, 4, 5});
auto& vec = std::any_cast<std::vector<int>&>(a); // 获取引用,避免拷贝
std::cout << "emplace vector 大小: " << vec.size() << std::endl;
}
// ============================
// 示例4:异构容器
// ============================
void heterogeneous_container() {
std::vector<std::any> bag;
bag.push_back(42);
bag.push_back(std::string("hello"));
bag.push_back(3.14);
bag.push_back(true);
for (const auto& item : bag) {
// 检查每种类型
if (item.type() == typeid(int)) {
std::cout << "[int] " << std::any_cast<int>(item) << std::endl;
} else if (item.type() == typeid(std::string)) {
std::cout << "[string] " << std::any_cast<std::string>(item) << std::endl;
} else if (item.type() == typeid(double)) {
std::cout << "[double] " << std::any_cast<double>(item) << std::endl;
} else if (item.type() == typeid(bool)) {
std::cout << "[bool] " << std::boolalpha << std::any_cast<bool>(item) << std::endl;
}
}
}
// ============================
// 示例5:any_cast 获取引用(避免拷贝)
// ============================
void reference_cast_demo() {
std::any a = std::string("original");
// any_cast<T&> 获取引用,直接修改存储的值
std::any_cast<std::string&>(a) = "modified";
std::cout << "修改后: " << std::any_cast<std::string>(a) << std::endl;
// any_cast<const T&> 获取 const 引用
const auto& ref = std::any_cast<const std::string&>(a);
std::cout << "const 引用: " << ref << std::endl;
}
int main() {
std::cout << "=== 基本使用 ===" << std::endl;
basic_usage();
std::cout << "\n=== 安全转换 ===" << std::endl;
safe_cast_demo();
std::cout << "\n=== make_any 和 emplace ===" << std::endl;
make_and_emplace_demo();
std::cout << "\n=== 异构容器 ===" << std::endl;
heterogeneous_container();
std::cout << "\n=== 引用转换 ===" << std::endl;
reference_cast_demo();
return 0;
}与相关类型的对比
| 特性 | std::any | std::variant | std::optional | void* |
|---|---|---|---|---|
| 可存储类型 | 任意可拷贝类型 | 编译期固定列表 | 单一类型 | 任意 |
| 类型安全 | 运行时检查 | 编译期保证 | 编译期保证 | 不安全 |
| 堆分配 | 大对象可能需要 | 不需要 | 不需要 | 取决于用法 |
| 能否为空 | 可以 | 不能(除非 monostate) | 可以 | 可以 |
| 访问方式 | any_cast | get / visit | value() / * | 强制转换 |
| 编译期类型完备性检查 | 不支持 | visit 强制处理所有类型 | N/A | 不支持 |
| 性能 | 较低(类型擦除开销) | 较高 | 高 | 高(但不安全) |
进阶用法
#include <iostream>
#include <any>
#include <string>
#include <unordered_map>
#include <functional>
// ============================
// 进阶1:属性系统(键值对,值为任意类型)
// ============================
class PropertyBag {
std::unordered_map<std::string, std::any> properties_;
public:
// 设置属性
template<typename T>
void set(const std::string& key, T&& value) {
properties_[key] = std::forward<T>(value);
}
// 获取属性(返回 optional 更安全)
template<typename T>
std::optional<T> get(const std::string& key) const {
auto it = properties_.find(key);
if (it == properties_.end()) return std::nullopt;
if (auto* p = std::any_cast<T>(&it->second)) {
return *p;
}
return std::nullopt;
}
// 检查是否存在
bool has(const std::string& key) const {
return properties_.count(key) > 0;
}
};
// ============================
// 进阶2:消息/事件系统
// ============================
struct Event {
std::string name;
std::any data; // 不同事件携带不同类型的数据
};
void handle_event(const Event& evt) {
if (evt.name == "click") {
// click 事件携带坐标 pair
if (auto* pos = std::any_cast<std::pair<int, int>>(&evt.data)) {
std::cout << "点击位置: (" << pos->first << ", " << pos->second << ")" << std::endl;
}
} else if (evt.name == "message") {
// message 事件携带字符串
if (auto* msg = std::any_cast<std::string>(&evt.data)) {
std::cout << "消息: " << *msg << std::endl;
}
}
}
int main() {
// 属性系统
PropertyBag bag;
bag.set("name", std::string("MyApp"));
bag.set("version", 2);
bag.set("debug", true);
std::cout << "name: " << bag.get<std::string>("name").value_or("unknown") << std::endl;
std::cout << "version: " << bag.get<int>("version").value_or(0) << std::endl;
std::cout << "debug: " << std::boolalpha << bag.get<bool>("debug").value_or(false) << std::endl;
std::cout << "missing: " << bag.get<int>("missing").value_or(-1) << std::endl;
// 事件系统
std::cout << "\n=== 事件系统 ===" << std::endl;
Event click_evt{"click", std::make_pair(100, 200)};
Event msg_evt{"message", std::string("hello!")};
handle_event(click_evt);
handle_event(msg_evt);
return 0;
}适用场景
- 属性系统 / 配置系统:键值对中值的类型不固定
- 消息 / 事件系统:不同消息携带不同类型的负载数据
- 插件架构:插件向宿主传递任意类型的数据
- 需要类型安全的
void*的场景 - 与脚本语言或动态类型系统的交互层
常见问题
std::any 存储大对象时会堆分配吗?
标准鼓励实现对小对象进行小缓冲区优化(SBO):如果值足够小且有不抛异常的移动构造函数,直接存在 any 对象内部,不堆分配。具体阈值取决于实现:MSVC 的 SBO 缓冲区是 64 字节(足够存储大多数基本类型),GCC 和 Clang 通常是 16 或 32 字节。大对象会堆分配。
any_cast 的值版本和指针版本怎么选?
如果你确定类型匹配(或者希望类型不匹配时抛异常处理),用值版本 std::any_cast<T>(a)。如果你不确定类型,想安全地"试一下",用指针版本 std::any_cast<T>(&a)——返回 nullptr 表示不匹配,没有异常开销。
std::any 对存储的类型有什么要求?
存储的类型必须是可拷贝构造的(CopyConstructible)。只有移动构造函数的类型(比如 std::unique_ptr)不能存入 std::any。如果你需要存储不可拷贝的类型,考虑用 shared_ptr 包装后再存入。
什么时候该用 any,什么时候用 variant?
如果你在编译期就知道所有可能的类型,用 variant——它更高效,编译器能帮你做完备性检查。如果类型列表不确定或开放式的(比如插件系统、属性包),用 any。
注意事项
std::any只能存储可拷贝构造的类型,std::unique_ptr等仅移动类型不行- 大对象存入 any 可能触发堆分配,注意性能敏感场景
any_cast必须精确匹配类型:any存的是int,用any_cast<long>也会失败type()返回的type_info的name()在不同编译器上输出格式不同any的拷贝会拷贝存储的值(深拷贝),不是共享- 不要把
std::any当作万能容器滥用——如果类型固定,variant或optional更合适
编译器支持情况
| 编译器 | 最低支持版本 |
|---|---|
| GCC | 7.0 |
| Clang | 4.0 |
| MSVC | 19.10 (VS 2017) |
总结
std::any 是 C++17 提供的类型安全的万能值容器,可以存储任意可拷贝构造类型的值。它通过类型擦除技术在内部记录存储的实际类型,通过 any_cast 提供类型安全的访问。和 void* 相比,any 知道自己存了什么类型,转换错误会抛异常或返回 nullptr 而不是产生未定义行为。和 variant 相比,any 更灵活(不需要编译期固定类型列表),但代价是可能的堆分配和运行时类型检查开销。最佳实践是:只在类型列表真正不确定的场景下使用 any(属性系统、插件架构等),类型已知时优先用 variant 或 optional。