如何在编译时查找类型为 T 的元组元素的索引?

问题描述 投票:0回答:1

我想找到 T 类型元组元素的索引。 我想在编译时执行此操作。 怎么做? 每个类型只会在元组中使用一次,因此类型将是唯一的。

这是我到目前为止所拥有的:

using Tuple_Type = std::tuple
<
    CoolType,
    SomethingElse,
    Boing,
    BingBang
>;

Tuple_Type  m_pool_of_data;


template <typename T>
inline T& Get()
{
    return std::get<T>(m_pool_of_data);     // This one works great
}

template <typename T>
inline int GetIndexOfType()
{
    return ??????;    // How to make this work?
}


Boing b = Get<Boing>();     // Gets the element of type Boing from the tuple
int index_of_type = GetIndexOfType<Boing>();    // Should return 2

如何使 int GetIndexOfType() 工作?

c++ templates tuples
1个回答
0
投票

使用 c++20 模板 lambda 的答案:

template <typename Tuple, typename T>
constexpr int GetIndexOfType()
{
    return []<typename... Ts>(std::type_identity<std::tuple<Ts...>> t){
        std::size_t index = 0;
        (void)((++index, std::is_same_v<Ts, T>) || ...);
        return index - 1;
    }(std::type_identity<Tuple>{});
}

折叠表达式是一种复杂的方式,表示“当类型不同时,增加索引”。

尽管更规范的方法是按照评论中的建议使用

std::index_sequence

演示:https://godbolt.org/z/1hPvcndzc

© www.soinside.com 2019 - 2024. All rights reserved.