std:: make_any
From cppreference.net
C++
Utilities library
|
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
定义于头文件
<any>
|
||
|
template
<
class
T,
class
...
Args
>
std:: any make_any ( Args && ... args ) ; |
(1) | (C++17 起) |
|
template
<
class
T,
class
U,
class
...
Args
>
std:: any make_any ( std:: initializer_list < U > il, Args && ... args ) ; |
(2) | (C++17 起) |
构造一个包含
T
类型对象的
any
对象,将提供的参数传递给
T
的构造函数。
1)
等价于
return
std::
any
(
std::
in_place_type
<
T
>
,
std::
forward
<
Args
>
(
args
)
...
)
;
2)
等价于
return
std::
any
(
std::
in_place_type
<
T
>
, il,
std::
forward
<
Args
>
(
args
)
...
)
;
示例
运行此代码
#include <any> #include <complex> #include <functional> #include <iostream> #include <string> int main() { auto a0 = std::make_any<std::string>("Hello, std::any!\n"); auto a1 = std::make_any<std::complex<double>>(0.1, 2.3); std::cout << std::any_cast<std::string&>(a0); std::cout << std::any_cast<std::complex<double>&>(a1) << '\n'; using lambda = std::function<void(void)>; // 将 lambda 表达式放入 std::any。尝试 #1(失败)。 std::any a2 = [] { std::cout << "Lambda #1.\n"; }; std::cout << "a2.type() = \"" << a2.type().name() << "\"\n"; // any_cast 尝试转换为 <void(void)>,但实际类型并非 // std::function...,而是 ~ main::{lambda()#1},且每个 // lambda 的类型都是唯一的。因此,此处会抛出异常... try { std::any_cast<lambda>(a2)(); } catch (std::bad_any_cast const& ex) { std::cout << ex.what() << '\n'; } // 将 lambda 表达式放入 std::any。尝试 #2(成功)。 auto a3 = std::make_any<lambda>([] { std::cout << "Lambda #2.\n"; }); std::cout << "a3.type() = \"" << a3.type().name() << "\"\n"; std::any_cast<lambda>(a3)(); }
可能的输出:
Hello, std::any! (0.1,2.3) a2.type() = "Z4mainEUlvE_" bad any_cast a3.type() = "St8functionIFvvEE" Lambda #2.
参见
构造
any
对象
(公开成员函数) |
|
|
(C++17)
|
类型安全地访问所含对象
(函数模板) |