std::any:: any
|
constexpr
any
(
)
noexcept
;
|
(1) | (自 C++17 起) |
|
any
(
const
any
&
other
)
;
|
(2) | (自 C++17 起) |
|
any
(
any
&&
other
)
noexcept
;
|
(3) | (自 C++17 起) |
|
template
<
class
ValueType
>
any ( ValueType && value ) ; |
(4) | (自 C++17 起) |
|
template
<
class
ValueType,
class
...
Args
>
explicit any ( std:: in_place_type_t < ValueType > , Args && ... args ) ; |
(5) | (自 C++17 起) |
|
template
<
class
ValueType,
class
U,
class
...
Args
>
explicit
any
(
std::
in_place_type_t
<
ValueType
>
,
std::
initializer_list
<
U
>
il,
|
(6) | (自 C++17 起) |
构造一个新的
any
对象。
T
是
other
所含对象的类型。
-
此重载仅当
std::
decay_t
<
ValueType
>
与
any类型不同且不是 std::in_place_type_t 的特化,并且 std:: is_copy_constructible_v < std:: decay_t < ValueType >> 为 true 时参与重载决议。
- 仅当 std:: is_constructible_v < std:: decay_t < ValueType > , Args... > 与 std:: is_copy_constructible_v < std:: decay_t < ValueType >> 均为 true 时,此重载才参与重载决议。
- 此重载仅当 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 | - | 传递给所含对象构造函数的参数 |
异常
注释
由于默认构造函数是
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 demangle 打印 any 实例所持有类型的友好名称 void printType(const std::any& a) { std::cout << boost::core::demangle(a.type().name()) << '\n'; } int main() { // 构造函数 #4:持有 int 的 std::any std::any a1{7}; // 构造函数 #5:持有 A 的 std::any,就地构造 std::any a2(std::in_place_type<A>, 30, "Ada", 1000.25); // 构造函数 #6:持有自定义比较函数的 A 集合的 std::any 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
对象赋值
(公开成员函数) |