CppDS.com

C++ 98 11 14 17 20 手册

std::any_cast

来自cppreference.com
< cpp‎ | utility‎ | any
 
 
工具库
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)
swap 与类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++17)

初等字符串转换
(C++17)
(C++17)
 
 
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 起)

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

Ustd::remove_cv_t<std::remove_reference_t<T>>

1)is_constructible_v<T, const U&>true 则程序为病式。
2)is_constructible_v<T, U&>true 则程序为病式。
3)is_constructible_v<T, U>true 则程序为病式。

参数

operand - 目标 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 不是空指针,且请求的 Ttypeid 匹配 operandtypeid ,则为指向所含值的指针,否则为空指针。

异常

1-3) 若请求的 Ttypeid 不匹配 operand 内容的 typeid ,则抛出 std::bad_any_cast

示例

#include <string>
#include <iostream>
#include <any>
#include <utility>
 
int main()
{
    // 简单示例
 
    auto a = std::any(12);
 
    std::cout << std::any_cast<int>(a) << '\n'; 
 
    try {
        std::cout << std::any_cast<std::string>(a) << '\n';
    }
    catch(const std::bad_any_cast& e) {
        std::cout << e.what() << '\n';
    }
 
    // 指针示例
 
    if (int* i = std::any_cast<int>(&a)) {
       std::cout << "a is int: " << *i << '\n';
    } else if (std::string* s = std::any_cast<std::string>(&a)) {
       std::cout << "a is std::string: " << *s << '\n';
    } else {
       std::cout << "a is another type or unset\n";
    }
 
    // 进阶示例
 
    a = std::string("hello");
 
    auto& ra = std::any_cast<std::string&>(a); //< 引用
    ra[1] = 'o';
 
    std::cout << "a: "
        << std::any_cast<const std::string&>(a) << '\n'; //< const 引用
 
    auto b = std::any_cast<std::string&&>(std::move(a)); //< 右值引用
 
    // 注意: 'b' 是移动构造的 std::string , 'a' 被置于合法但未指定的状态
 
    std::cout << "a: " << *std::any_cast<std::string>(&a) //< 指针
        << "b: " << b << '\n';
}

可能的输出:

12
bad any_cast
a is int: 12
a: hollo
a: b: hollo
关闭