如何将TypeList还原回其原始参数包 [英] How to Revert a TypeList back to its original parameter pack

查看:47
本文介绍了如何将TypeList还原回其原始参数包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在查找有关如何将c ++ 11可变参数TypeList用作可移植参数包的容器方面遇到困难.可以说我有这段代码.

I'm having trouble finding information on how to use c++11 variadic TypeLists as containers for portable parameter packs. Lets say I had this piece of code.

#include <type_traits>

template <typename T, typename... Ts>
struct Index;

template <typename T, typename... Ts>
struct Index<T, T, Ts...> : std::integral_constant<std::size_t, 0> {};

template <typename T, typename U, typename... Ts>
struct Index<T, U, Ts...> : std::integral_constant<std::size_t, 1 + Index<T, Ts...>::value> {};

我可以用它来找到像这样的参数包内部类型的第一个索引.

I can use it to find the first index of a type inside of a parameter pack like this.

int main() 
{
using namespace std;

cout << Index<int, int>::value << endl;                //Prints 0
cout << Index<char, float, char>::value << endl;       //Prints 1
cout << Index<int, double, char, int>::value << endl;  //Prints 2
}

如何为TypeList实现此行为?我正在尝试创建类似这样的东西.

How could I achieve this behavior for a TypeList? I'm trying to create something like this.

template <typename ...>
struct TypeList {};

int main() 
{
using namespace std;
using List = TypeList<char, short, long>

cout << Index<short, ConvertToParameterPack<List>::types...>::value << endl;  //Prints 1
}

其中ConvertToParameterPack是将TypeList还原回其ParameterPack的某种方法.如果我要问的是不可能的,还有其他好的方法可以解决这个问题吗?

Where ConvertToParameterPack is some method of reverting a TypeList back to its ParameterPack. If what I'm asking is impossible, are there any other good ways to solve this?

推荐答案

template<std::size_t I>
using index_t=std::integral_constant<std::size_t,I>;

template<class T, class List>
struct Index{}; 

template<class T, class...Ts>
struct Index<T, TypeList<T,Ts...>>:
  index_t<0>
{};

template<class T,class U, class...Ts>
struct Index<T, TypeList<U,Ts...>>:
  index_t< 1+Index<T,TypeList<Ts...>::value >
{}

这篇关于如何将TypeList还原回其原始参数包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆