c++ - 正确使用 std::variant_alternative_t
问题描述
我的目标是在 std::variant 的当前索引处获取类型的名称。我所知道的是变量的当前索引。我尝试了不同的方法,但老实说,我在很大程度上无法理解文档(cppreference)。如果没有一段工作代码,所有这些重载的模板对我来说都是很复杂的。
我猜 std::variant_alternative_t 可能会有所帮助,但文档不完整(没有示例:https ://en.cppreference.com/w/cpp/utility/variant/variant_alternative )。
让我们假设以下示例。
std::variant<int, float> testVariant{ 12.2f };
std::cout << std::get<1>(testVariant); // Everything is cool
//std::cout << std::get<testVariant.index()>(testVariant) // Unfortunately, incorrect syntax
//... why ever, i dont see any difference to the line above
//std::variant_alternative_t<???>(???) i dont have any cloud how to use it
解决方案
正确的用法涉及两个模板参数:索引和要索引到的变体类型。
using MyIndexedType = std::variant_alternative_t<1, std::variant<int, float>>;
或者,如果您既不想拼出完整的变体,也不想给它一个类型别名 ( using MyVariant = std::variant<int, float>
),请使用decltype
:
using MyIndexedType = std::variant_alternative_t<1, decltype(testVariant)>;
请注意,索引必须在编译时已知。您无法在编译时了解所有静态类型。
推荐阅读
- html - 错误的样式颜色可视化但仅在真实的移动设备上
- python - 如何从 Google Drive 下载多个文本文件并附加到 Pandas 数据框?
- vue.js - 如何在 vue 中使用 grpc-web?
- c# - ASP.NET Core 如何让 UserManager 在控制器中工作?
- nestjs - 当 html 页面在保存时重新加载时,Nestjs/Angular Universal 在节点控制台中输出错误
- c# - Visual Studios 中的正则表达式否定搜索查找/替换
- node.js - 使用 Node 创建系统托盘图标
- concurrency - Kamailio 伪变量 $var 在单个消息处理程序结束之前是否可以安全使用?
- javascript - 使用 selenium 和 python 保存/提交网络表单的问题
- windows - 如何摆脱“c_MAMPRO_unins000_exe”