金融公司网站免费模板百度快速优化软件排名
基础概念
std::any是一个可以存储任意类型的数据类型安全的容器,它的特点是主要是:
- 可以存储任意类型的单个值
- 在运行时保持类型安全
- 需要显示的类型转化才能取出值
依赖的头文件:#include <any>
基本用法
#include <any>
#include <iostream>
#include <string>int main()
{//基本构造和赋值std::any a1;std::any a2 = 42;std::any a3 = std::string("hello");//使用make_any构造auto a3 = std::make_any<std::string>("world");//检查是否为空std::cout <<"是否为空:"<<std::boolalpha<<a1.has_value()<<std::endl;//获取存储值的类型信息std::cout <<"a2的类型信息:"<<a2.type().name()<<std::endl;//获取值int value = std::any_cast<int>(a2); //必须使用any_cast<T>显式的转换std::cout <<"a2的值:"<<value<<std::endl; return 0;}
错误的用法
假设std::any存储的数据类型是整型,但是却通过std::any_cast<T>却强转为其它类型,那么就会抛出异常,请看下面的例子:
void error_example()
{try {std::any number = 42;// 错误的类型转换std::string str = std::any_cast<std::string>(number);}catch(const std::bad_any_cast& e) {std::cout << "类型转换失败: " << e.what() << "\n";}}
使用建议
- 当需要存储未知类型的数据时使用
- 如果类型集合是已知的,考虑使用
std::variant
- 注意异常处理
- 合理使用类型检查和转换机制