std::any是C++17引入的类型安全容器,可存储任意可复制类型,需包含<any>头文件并启用C++17,适用于配置项、参数传递等场景,通过std::any_cast安全访问值,支持指针检查避免异常,可用于混合类型容器但需注意性能开销和类型安全,不支持不可复制类型,应避免滥用。

std::any 是 C++17 引入的一个类型安全的容器,可以保存任意类型的值。它属于 <any> 头文件,适合在不知道具体类型或需要动态存储不同类型值的场景中使用,比如配置项、参数传递、插件系统等。
std::any 需要编译器支持 C++17 或更高版本。
#include <iostream>
#include <any>
#include <string>
#include <vector>
int main() {
// 示例代码
std::any value = 42;
std::cout << "Stored int: " << std::any_cast<int>(value) << std::endl;
return 0;
}编译时加上 -std=c++17:
g++ -std=c++17 any_example.cpp -o any_example
std::any 可以赋值为任意可复制的类型。
std::any a = 100; // 存整数
a = std::string("hello"); // 替换为字符串
a = 3.14; // 替换为浮点数从 std::any 中取出值使用 std::any_cast<t></t>:
try {
int n = std::any_cast<int>(a); // 错误:当前是 double 类型
} catch (const std::bad_any_cast&) {
std::cout << "Type mismatch!" << std::endl;
}
double d = std::any_cast<double>(a); // 正确
std::cout << d << std::endl;也可以使用指针形式避免异常:
立即学习“C++免费学习笔记(深入)”;
double* p = std::any_cast<double>(&a);
if (p) {
std::cout << "Value: " << *p << std::endl;
} else {
std::cout << "Not a double" << std::endl;
}std::vector<std::any> 存储多种类型的数据(谨慎使用,避免滥用)。
std::vector<std::any> items;
items.push_back(42);
items.push_back(std::string("text"));
items.push_back(true);
for (const auto& item : items) {
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<const std::string&>(item) << std::endl;
} else if (item.type() == typeid(bool)) {
std::cout << "bool: " << std::any_cast<bool>(item) << std::endl;
}
}std::any 有运行时类型检查和堆分配开销。
- 类型安全:错误的 any_cast 会抛出 std::bad_any_cast,建议配合 try-catch 或指针检查。
- 不要过度使用:仅在确实需要类型泛化时使用,优先考虑模板或多态。
- 不可复制类型不支持:如果类型没有拷贝构造函数,不能存入 std::any。
基本上就这些。std::any 提供了类型安全的“万能盒子”,合理使用能让代码更灵活。
以上就是c++++怎么使用std::any_c++ std::any类型使用与示例的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号