Namespaces
Variants

std::any_cast

来自 zh.cppreference.net
< cpp | 工具 | any
 
 
 
 
定义于头文件 <any>
template< class T >
T any_cast( const any& operand );
(1) (C++17 起)
template< class T >
T any_cast( any& operand );
(2) (C++17 起)
template< class T >
T any_cast( any&& operand );
(3) (C++17 起)
template< class T >
const T* any_cast( const any* operand ) noexcept;
(4) (C++17 起)
template< class T >
T* any_cast( any* operand ) noexcept;
(5) (C++17 起)

对所含对象执行类型安全的访问。

令 U 为 std::remove_cv_t<std::remove_reference_t<T>>。

1) 若 std::is_constructible_v<T, const U&> 为 false 则程序非良构。
2) 若 std::is_constructible_v<T, U&> 为 false 则程序非良构。
3) 若 std::is_constructible_v<T, U> 为 false 则程序非良构。
4,5) 若 std::is_void_v<T> 为 true 则程序非良构。

参数

操作数 - 目标 any 对象

返回值

1,2) 返回 static_cast < T > ( * std :: any_cast < U > ( & operand ) ) 。
3) 返回 static_cast < T > ( std :: move ( * std :: any_cast < U > ( & operand ) ) ) 。
4,5) 若 operand 不是空指针,且所请求的 T 的 typeid 与 operand 所含内容的类型标识匹配,则返回指向操作数所含值的指针,否则返回空指针。

异常

1-3) 若请求的 T 的 typeid 与 operand 所含内容的类型不匹配,则抛出 std::bad_any_cast 。

示例

#include <any>
#include <iostream>
#include <string>
#include <type_traits>
#include <utility>
int main()
{
    // 简单示例
    auto a1 = std::any(12);
    std::cout << "1) a1 is int: " << std::any_cast<int>(a1) << '\n';
    try
    {
        auto s = std::any_cast<std::string>(a1); // 抛出异常
    }
    catch (const std::bad_any_cast& e)
    {
        std::cout << "2) " << e.what() << '\n';
    }
    // 指针示例
    if (int* i = std::any_cast<int>(&a1))
        std::cout << "3) a1 is int: " << *i << '\n';
    else if (std::string* s = std::any_cast<std::string>(&a1))
        std::cout << "3) a1 is std::string: " << *s << '\n';
    else
        std::cout << "3) a1 is another type or unset\n";
    // 高级示例
    a1 = std::string("hello");
    auto& ra = std::any_cast<std::string&>(a1); // 引用
    ra[1] = 'o';
    std::cout << "4) a1 is string: "
              << std::any_cast<const std::string&>(a1) << '\n'; // 常量引用
    auto s1 = std::any_cast<std::string&&>(std::move(a1)); // 右值引用
    // 注意:"s1" 是通过移动构造的 std::string
    static_assert(std::is_same_v<decltype(s1), std::string>);
    // 注意:"a1" 中的 std::string 处于有效但未指定的状态
    std::cout << "5) a1.size(): "
              << std::any_cast<std::string>(&a1)->size() // 指针
              << '\n'
              << "6) s1: " << s1 << '\n';
}

可能的输出:

1) a1 is int: 12
2) bad any_cast
3) a1 is int: 12
4) a1 is string: hollo
5) a1.size(): 0
6) s1: hollo

缺陷报告

下列行为变更缺陷报告被追溯应用于先前发布的 C++ 标准。

缺陷报告 适用范围 发布时行为 正确行为
LWG 3305 C++17 当 T 为 void 时,重载 ( 4,5 ) 的行为不明确 此情况下程序格式错误