和 void* 有什么区别?
// void*:完全不安全
void* storage = new int(42);
// 一年后别的开发者:
int* p = static_cast<int*>(storage); // 假设有人告诉他是 int
// 但如果存储的是 double 呢?💥
// std::any:安全
std::any storage = 42;
storage = 3.14;
storage = std::string("hello");
// 取出时必须指定类型,错了就抛异常
try {
int val = std::any_cast<int>(storage); // ❌ 当前是 string
} catch (const std::bad_any_cast&) {
std::cout << "wrong type";
}
什么时候真的需要 any?
很少。variant 比 any 更好(variant 在编译期知道可能的类型集,any 不知道)。
少数的场景:插件系统/动态配置系统,你需要存储"类型完全未知、运行时才能确定"的数据:
// 配置系统:每个配置项的类型只能在加载时确定
std::unordered_map<std::string, std::any> runtime_config;
runtime_config["timeout"] = 30; // int
runtime_config["rate"] = 3.14; // double
runtime_config["name"] = "server"s; // string
// 运行时才知道类型
std::string key = get_user_input(); // 用户输入 "rate"
if (runtime_config[key].has_value()) {
// 但这里不知道是 int 还是 double,只能 try 所有类型
}
能用 variant 的场景就别用 any,因为 any 底层用虚表做类型擦除,每次 any_cast 都有一次 RTTI 比较。