如何在编译时查找std::tuple中指定类型T的元素索引?
编译时获取std::tuple中指定类型的索引
问题背景
我需要在编译时找到std::tuple中类型为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); // 这个函数运行正常 } template <typename T> inline int GetIndexOfType() { return ??????; // 如何实现这个函数? } Boing b = Get<Boing>(); // 从元组中获取Boing类型的元素 int index_of_type = GetIndexOfType<Boing>(); // 应返回2
目前Get()函数可正常获取对应类型元素,但GetIndexOfType()函数的实现遇到了困难。我使用的是C++17,此外还存在一个问题:std::get可以区分通过using定义的不同别名类型(如using Boing = int; using BingBang = int;),但std::is_same_v会将它们视为同一类型,这给实现带来了困扰。
最终解决方案
我基于反馈实现了可行的解决方案:
template <typename T, int I> static constexpr int GetTypeIndexFromTuple() { constexpr int tuple_element_count = std::tuple_size<Tuple_Type>(); // 未找到对应类型? if constexpr (I >= tuple_element_count) { return -1; } else { // 找到对应类型? if constexpr (std::is_same_v<std::tuple_element_t<I, Tuple_Type>, T>) return I; else return GetTypeIndexFromTuple<T, I + 1>(); // 检查下一个元组元素 } } template <typename T> inline int GetTypeIndex() { int index = GetTypeIndexFromTuple<T, 0>(); assert(index != -1); return index; }
该方案可正常运行,同时我将非结构体/类的类型封装进结构体以解决类型冲突问题,该系统用于我开发的一个专用容器类中。
内容的提问来源于stack exchange,提问作者user19179144
相关产品推荐
相关产品推荐

