std::any::any
来自cppreference.com
| |
(1) | (C++17 起) |
| |
(2) | (C++17 起) |
| |
(3) | (C++17 起) |
| |
(4) | (C++17 起) |
| |
(5) | (C++17 起) |
| |
(6) | (C++17 起) |
构造新的 any 对象。
1) 构造空对象。
2,3) 复制 (2) 或移动 (3)
other 的内容进新实例,从而任何内容的类型和值都等于构造函数调用前的 other 所拥有者,或者若 other 为空则内容为空。正式地说,2) 若
other 为空,则构造的对象为空。否则,等价于 any(std::in_place_type<T>, std::any_cast<const T&>(other)),其中 T 是 other 中含有的对象类型。3) 若
other 为空,则构造的对象为空,否则,构造的对象含 other 中曾容纳的对象,或从 other 中的对象(将该对象当作右值)构造的同类型对象。4) 构造对象,其初始内容为
std::decay_t<ValueType> 类型的对象,从 std::forward<ValueType>(value) 直接初始化它。
- 此重载只有在
std::decay_t<ValueType>既非与any相同类型,亦非std::in_place_type_t 的特化,且std::is_copy_constructible_v<std::decay_t<ValueType>>为true时才会参与重载决议。
5) 构造对象,其初始内容为
std::decay_t<ValueType> 类型的对象,从 std::forward<Args>(args)... 直接非列表初始化它。
- 此重载只有在
std::is_constructible_v<std::decay_t<ValueType>, Args...>与std::is_copy_constructible_v<std::decay_t<ValueType>>皆为true时才会参与重载决议。
6) 构造对象,其初始内容为
std::decay_t<ValueType> 类型的对象,从 il, std::forward<Args>(args)... 直接非列表初始化它。
- 此重载只有在
std::is_constructible_v<std::decay_t<ValueType>, std::initializer_list<U>&, Args...>与std::is_copy_constructible_v<std::decay_t<ValueType>>皆为true时才会参与重载决议。
模板形参
| ValueType | - | 所含的值类型 |
| 类型要求 | ||
-std::decay_t<ValueType> 必须满足可复制构造 (CopyConstructible) 。
| ||
参数
| other | - | 另一个用以复制或移动的 any 对象
|
| value | - | 用于初始化所含值的值 |
| il, args | - | 要传递给所含对象的构造函数的实参 |
异常
2,4-6) 抛出所含类型的构造函数所抛出的任何异常
注解
因为默认构造函数为 constexpr,所以静态的 std::any 是在任何动态非局部初始化开始之前,作为静态非局部初始化的一部分初始化的。这使得在任何静态对象的构造函数中使用 std::any 对象是安全的。
示例
运行此代码
#include <boost/core/demangle.hpp>
#include <any>
#include <initializer_list>
#include <iostream>
#include <memory>
#include <set>
#include <string>
#include <utility>
struct A
{
int age;
std::string name;
double salary;
#if __cpp_aggregate_paren_init < 201902L
// C++20 前进行原位构造所需
A(int age, std::string name, double salary)
: age(age), name(std::move(name)), salary(salary) {}
#endif
};
// 使用 abi 去重整,以打印 any 所持有的实例的可读类型名
void printType(const std::any& a)
{
std::cout << boost::core::demangle(a.type().name()) << '\n';
}
int main()
{
// 构造函数 #4: std::any 持有 int
std::any a1{7};
// 构造函数 #5: std::any 持有原位构造的 A
std::any a2(std::in_place_type<A>, 30, "Ada", 1000.25);
// 构造函数 #6: std::any 持有带有自定义比较的 A 的 set
auto lambda = [](auto&& l, auto&& r){ return l.age < r.age; };
std::any a3(
std::in_place_type<std::set<A, decltype(lambda)>>,
{
A{39, std::string{"Ada"}, 100.25},
A{20, std::string{"Bob"}, 75.5}
},
lambda);
printType(a1);
printType(a2);
printType(a3);
}
可能的输出:
int
A
std::set<A, main::{lambda(auto:1&&, auto:2&&)#1}, std::allocator<A> >
参阅
赋值 any 对象 (公开成员函数) |