c++ std::Any 用法
📅 2026/7/6 1:48:12
👁️ 阅读次数
📝 编程学习
据说std::Any能存任意值,测试下:
Test1.h:
#pragma once void testAny(void);Test1.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不能存引用类型,其他都可以存。
编程学习
技术分享
实战经验