variant中的类型获取索引

variant中的类型获取索引

本文介绍了按std :: variant中的类型获取索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标准库中是否有实用程序可在 std :: variant 类型的 index >?还是我应该自己做一个?也就是说,我想在 std :: variant< A,B,C> 中获得 B 的索引,然后有返回 1

Is there a utility in the standard library to get the index of a given type in std::variant? Or should I make one for myself? That is, I want to get the index of B in std::variant<A, B, C> and have that return 1.

std :: variant_alternative 用于相反的操作。当然,在 std :: variant 的列表上可能有许多相同的类型,因此此操作不是双向的,但对我来说不是问题(我可以在列表上首次出现类型,或者在 std :: variant 列表上具有唯一类型)。

There is std::variant_alternative for the opposite operation. Of course, there could be many same types on std::variant's list, so this operation is not a bijection, but it isn't a problem for me (I can have first occurrence of type on list, or unique types on std::variant list).

推荐答案

我找到了答案对于元组并对其进行了稍微修改:

I found this answer for tuple and slightly modificated it:

template<typename VariantType, typename T, std::size_t index = 0>
constexpr std::size_t variant_index() {
    if constexpr (index == std::variant_size_v<VariantType>) {
        return index;
    } else if constexpr (std::is_same_v<std::variant_alternative_t<index, VariantType>, T>) {
        return index;
    } else {
        return variant_index<VariantType, T, index + 1>();
    }
}

它对我有用,但是现在我很好奇如果作为结构,如何在没有constexpr的情况下以旧方式进行操作。

It works for me, but now I'm curious how to do it in old way without constexpr if, as a structure.

这篇关于按std :: variant中的类型获取索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 00:46