c++ std::Any 用法

据说std::Any能存任意值,测试下:

Test1.h:

cpp 复制代码
#pragma once

void testAny(void);

Test1.cpp:

cpp 复制代码
#include "Test1.h"
#include <any>
#include <string>
#include <iostream>

void testAny(void) {
    std::any a = 9527;
    std::cout << "a: " << *(std::any_cast<int>(&a)) << std::endl;  // 这里转化为指针再解引用
    int b = std::any_cast<int>(a); // 直接值传递
    std::cout << "b: " << b << std::endl;
    std::any c = std::string("日月之行,若出其中;星汉灿烂,若出其里。");
    a = '\n';
    a = c;
    auto p = std::any_cast<std::string>(&a); // 为了取值,做类型转化, p是指针. 如果类型不匹配转化失败, p为nullptr
    std::cout << "a: " << *p << std::endl;

    if (a.has_value()) {
        std::cout << "a 类型: " <<  a.type().name() << std::endl;
    }

    a.reset();

    if (a.has_value()) {
        std::cout << "a 有值 "<< std::endl;
    } else {
        std::cout << "a 没有值了,释放了。 "<< std::endl;
    }

}

运行:

ok. 据说any不能存引用类型,其他都可以存。

相关推荐
小杍随笔1 小时前
【Rust全栈项目接入UUID主键实战:从选型到PostgreSQL适配(含v7优化)】
开发语言·postgresql·rust
binbin_521 小时前
Flutter 调用鸿蒙原生组件:MethodChannel 与 PlatformView 的选择和落地
开发语言·深度学习·flutter·harmonyos
无限的鲜花10 小时前
反射(原创推荐)
java·开发语言
yongche_shi10 小时前
ragas官方文档中文版(五十)
开发语言·python·ai·ragas·如何评估和改进 rag 应用
一路向北he10 小时前
字节钢铁军团--“提供情境,而非控制”
java·开发语言·前端
QiLinkOS11 小时前
第三视觉理解徐玉生与他的商业活动(30)
大数据·c++·人工智能·算法·开源协议
mit6.82411 小时前
阅读的核心,是再读
c++
AI行业学习12 小时前
Notepad++ 官方下载 + 完整安装 + 全套优化配置(2026最新)
开发语言·人工智能·python·前端框架·html·notepad++
大圣编程12 小时前
Python中continue语句的用法是什么?
开发语言·前端·python