首页 > 解决方案 > 正确使用 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

标签: c++

解决方案


正确的用法涉及两个模板参数:索引和要索引到的变体类型。

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)>;

请注意,索引必须在编译时已知。您无法在编译时了解所有静态类型。


推荐阅读