c++ variant用法

📅 发布时间:2026/7/9 2:06:10
c++ variant用法 variant是联合体相当于c语言的union 测试下void testVariant(void) { // 测试下variant // 声明一个可以存储 int、double 或 std::string 的 variant std::variantint, double, std::string v; // variant 默认会初始化为第一个类型int的默认值0 std::cout 默认值: std::getint(v) std::endl; // 赋值类型切换 v 1314520; // 当前存储 int v 3.14; // 当前存储 double v 心乱则音噪心静则音纯。心慌则音误心泰则音清。听诸葛亮弹琴如观其肺腑也我能为诸葛亮知音不胜荣幸。; // 当前存储 std::string // 检查当前持有的类型 if (std::holds_alternativestd::string(v)) { std::cout 当前类型是字符串: std::getstd::string(v) std::endl; } // 异常处理如果类型不匹配std::get 会抛出异常 try { std::cout std::getint(v) std::endl; // 当前是 string强转 int 会报错 } catch (const std::bad_variant_access e) { std::cout 捕获异常: 当前 variant 中不存储 int 类型error: e.what() std::endl; } // 最推荐的访问方式std::visit (访问者模式) // 无论当前是什么类型都能安全处理 std::visit([](auto arg) { std::cout 当前类型是: typeid(arg).name() std::endl; std::cout 当前值: arg std::endl; }, v); // 或者这样 std::visit([](auto arg) { using T std::decay_tdecltype(arg); // 获取 arg 的实际类型 if constexpr (std::is_same_vT, int) { std::cout 收到整数: arg std::endl; } else if constexpr (std::is_same_vT, double) { std::cout 收到浮点数: arg std::endl; } else if constexpr (std::is_same_vT, std::string) { std::cout 收到字符串: arg std::endl; } }, v); }运行ok.