admin管理员组文章数量:1434900
Using C++26's pack indexing, you can create a simple tuple of types like so:
template <typename... Ts>
struct type_tuple {
template <unsigned Index>
using get = Ts...[Index];
};
using T = type_tuple<int, float, double>::get<1>; // float
How can this be replicated in earlier C++ versions?
Using C++26's pack indexing, you can create a simple tuple of types like so:
template <typename... Ts>
struct type_tuple {
template <unsigned Index>
using get = Ts...[Index];
};
using T = type_tuple<int, float, double>::get<1>; // float
How can this be replicated in earlier C++ versions?
Share Improve this question edited Nov 16, 2024 at 23:17 HeliumHydride asked Nov 16, 2024 at 22:58 HeliumHydrideHeliumHydride 811 silver badge5 bronze badges2 Answers
Reset to default 5You can use std::tuple_element
. This will work in all C++ versions supporting parameter packs:
template <typename... Ts>
struct type_tuple {
template <std::size_t Index>
using get = typename std::tuple_element<Index, std::tuple<Ts...>>::type;
};
If you are interested how it is done inside std::tuple
, then it is as simple as this:
template <std::size_t Index, typename ...T>
struct NthType;
//{};
template <typename T0, typename ...T>
struct NthType<0, T0, T...>
{
using Type = T0;
};
template <std::size_t Index, typename T0, typename ...T>
struct NthType<Index, T0, T...>
{
using Type = typename NthType<Index-1, T...>::Type; // skip one type, decrease index
};
template <typename... Ts>
struct type_tuple {
template <unsigned Index>
using get = typename NthType<Index, Ts...>::Type;
};
So:
- Define helper class NthType<Index, T...>
- Specialize for Index = 0: NthType<0, T0, T...>::Type == T0
- Make linear search for Nth type: NthType<Idx, T0, T...>::Type == NthType<Idx - 1, T...>
Note, that in last point we skip first type from pack, and decrease the index. In many libraries (including std lib implementations) there are also specialization for Index==1 and Index==2 just for spead up. I am not sure that, but in some compilers I can imagine there are builtin functions to get nth type from a pack - similar to C++26 way.
Before C++11 (before introduction of variadic templates) - there was just 50 or so specialization of such NthType - so it works up to Index==50 (or so...)
本文标签: cHow can I make a tuple of types that can be accessed by index without pack indexingStack Overflow
版权声明:本文标题:c++ - How can I make a tuple of types that can be accessed by index without pack indexing? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745645016a2668082.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论