Namespaces
Variants

std::any:: any

From cppreference.net
Utilities library
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,

Args && ... args ) ;
(6) (自 C++17 起)

构造一个新的 any 对象。

1) 构造一个空对象。
2,3) other 的内容复制 (2) 或移动 (3) 到新实例中,使得任何内容在类型和值上都等同于构造函数调用前的 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 ) 进行 直接初始化
5) 构造一个对象,其初始内容为类型 std:: decay_t < ValueType > 的对象,该对象通过 直接非列表初始化 std:: forward < Args > ( args ) ... 初始化。
6) 构造一个对象,其初始内容为 std:: decay_t < ValueType > 类型的对象,该对象通过 直接非列表初始化 il, std:: forward < Args > ( args ) ... 进行初始化。

目录

模板参数

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 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 对象赋值
(公开成员函数)