CPP Weekly --C++17

C++17

std::any

std::any库,它是一种类型安全的容器,可以存储任意类型 的数据。与void*不同,std::any可以检查是否存储了值,并且可以安全地检索和转换存储的值。我们可以使用std::any_cast函数检索该值,并将其转换为期望的类型,如果类型匹配,则强制转换返回相应的地址指针,如果不匹配,则返回nullptr。若要修改该值,需要转换为对应的引用类型 。如果我们试图从std::any对象中检索不正确的类型,std::bad_any_cast异常将被抛出。此外,如果std::any对象没有存储任何值,则std::bad_any_cast异常也会被抛出。因此,在使用std::any_cast函数时应谨慎,最好使用std::any::has_value函数检查std::any对象是否包含值。

c 复制代码
#include <iostream>
#include <any>
#include <string>
#include <vector>
#include <exception>

int main(int argc, char** argv)
{
    std::any a;
    try {
        std::cout << std::any_cast<int>(a) << std::endl;
    } catch (std::exception& e) {
        std::cout << "Exception: " << e.what() << std::endl;
    }

    // check has value
    std::cout << "std::any::has_value(): " << a.has_value() << std::endl;
    // clear value
    a.reset();  // a = std::any{}; 或 a = {};

    std::cout << "std::any::has_value(): " << a.has_value() << std::endl;

    a = 1;
    std::cout << "std::any::has_value(): " << a.has_value() << std::endl;
    if (a.type() == typeid(int)) {
        std::cout << "std::any::has_value type int" << std::endl;
    }

    std::cout << std::any_cast<int>(a) << std::endl;

    a = 3.1415926;  // double
    std::cout << std::any_cast<double>(a) << std::endl;
    if (a.type() == typeid(double)) {
        std::cout << "std::any::has_value type double" << std::endl;
    }

    a = std::string("Hello");  // std::string
    std::cout << std::any_cast<std::string>(a) << std::endl;
    // modify value
    std::any_cast<std::string&>(a) = "World";
    std::cout << std::any_cast<std::string>(a) << std::endl;

    std::vector<int> v1 = {1, 2, 3, 4, 5};
    a                   = v1;  // vector
    std::vector<int> b  = std::any_cast<std::vector<int>>(a);
    for (auto i : b) {
        std::cout << i << " ";
    }
    std::cout << std::endl;

    a = {};  // clear value
    std::cout << "---------------------" << std::endl;
    std::vector<std::any> v2;
    v2.push_back(42);
    std::string s = "hello";
    v2.push_back(s);
    for (const auto& tmp : v2) {
        if (tmp.type() == typeid(std::string)) {
            std::cout << "type string: " << std::any_cast<const std::string&>(tmp) << std::endl;
        } else if (tmp.type() == typeid(int)) {
            std::cout << "type int: " << std::any_cast<int>(tmp) << std::endl;
        }
    }

    return 0;
}
相关推荐
妮妮喔妮38 分钟前
【无标题】
开发语言·前端·javascript
fie888943 分钟前
浅谈几种js设计模式
开发语言·javascript·设计模式
喝可乐的布偶猫1 小时前
Java类变量(静态变量)
java·开发语言·jvm
喝可乐的布偶猫1 小时前
韩顺平之第九章综合练习-----------房屋出租管理系统
java·开发语言·ide·eclipse
江山如画,佳人北望2 小时前
C#程序入门
开发语言·windows·c#
coding随想3 小时前
JavaScript中的BOM:Window对象全解析
开发语言·javascript·ecmascript
念九_ysl3 小时前
Java 使用 OpenHTMLToPDF + Batik 将含 SVG 遮罩的 HTML 转为 PDF 的完整实践
java·开发语言·pdf
yaoxin5211233 小时前
124. Java 泛型 - 有界类型参数
java·开发语言
liulilittle4 小时前
深度剖析:OPENPPP2 libtcpip 实现原理与架构设计
开发语言·网络·c++·tcp/ip·智能路由器·tcp·通信
88号技师4 小时前
2025年6月一区-田忌赛马优化算法Tianji’s horse racing optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法