且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

按std :: variant中的类型获取索引

更新时间:2022-06-02 06:21:31

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

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.