行业知识
C++三剑客之std::any(一) : 使用详解
相关系列文章
C++之std::tuple(二) : 揭秘底层实现原理
C++三剑客之std::optional(一) : 使用详解
C++三剑客之std::any(一) : 使用详解
C++之std::tuple(一) : 使用精讲(全)
C++三剑客之std::variant(一) : 使用
C++三剑客之std::variant(二):深入剖析
目录
1.概述
2.构建方式
2.1.构造函数
2.2.std::make_any
2.3.operator=分配新值
3.访问值std::any_cast
4.修改器
4.1.emplace
4.2.reset
4.3.swap
5.观察器
5.1.has_value
5.2.type
6.总结
1.概述
C++17的三剑客分别是std::optional, std::any, std::vairant。今天主要讲std::any。std::any类用于任何可拷贝构造类型的单个值的类型安全容器。在头文件中,c++标准库定义了类std::any。
namespace std {class any;} 从上面的定义可以看出std::any不是模版类,而是一种很特殊的容器,它只能容纳一个元素,但这个元素可以是任意的类型,可以是基本数据类型(int,double,char,float...)也可以是复合数据类型(类、结构体)。
std: any是一种值类型,它能够更改其类型,同时仍然具有类型安全性。也就是说,对象可以保存任意类型的值,但是它们知道当前保存的值是哪种类型。在声明此类型的对象时,不需要指定可能的类型。
2.构建方式
2.1.构造函数
默认情况下,std::any的初始值为空。如:
std::any a;
也可以赋初值,初始化对象std::any, 如:
std::any a = 32; //type: intstd::any b = "wegrthweg"; //type : const chr*
要保存与初始值类型不同的类型,必须使用in_place_type标记:
std::any a{std::in_place_type, 420};std::any b{std::in_place_type, "asdfbsrghtr34"}; 即使传递给in_place_type的类型也会退化。下面的声明包含一个const char*:
std::any a{std::in_place_type, "12345"}; 要通过多个参数初始化可选对象,必须创建该对象或将std::in_place_type添加为第一个参数(不能推断包含的类型):
std::any a1{std::complex{6.0, 2.0}};std::any a2{std::in_place_type, 6.0, 2.0}; 甚至可以传递一个初始化器列表,后面跟着附加的参数:
auto func = [] (int x, int y) { return std::abs(x) 2.2.std::make_any
std::make_any的定义如下:
//[1]templatestd::any make_any( Args&&... args );//[2]templatestd::any make_any( std::initializer_list il, Args&&... args );
构造含 T 类型对象的 any 对象,传递提供的参数给 T 的构造函数。
1) 等价于 return std::any(std::in_place_type, std::forward(args)...);
2) 等价于 return std::any(std::in_place_type, il, std::forward(args)...);
std::make_any必须显式指定初始化的类型(如果只传递一个参数,则不会推导出初始化的类型),如:
#include #include #include #include #include int main(){ auto a0 = std::make_any("Hello, std::any!\n"); auto a1 = std::make_any(0.1, 2.3); std::cout