如何获取变量类型包中的类型的索引? [英] How to get the index of a type in a variadic type pack?

查看:146
本文介绍了如何获取变量类型包中的类型的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如

template<typename T, typename... Ts>
struct Index
{
    enum {value = ???}
};

并且假定T是T s之一并且T s具有不同的类型,例如

and assume T is one of Ts and Ts has different types, like

Index<int, int, double>::value is 0
Index<double, int, double>::value is 1


推荐答案

#include <type_traits>
#include <cstddef>

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> {};

您可能希望添加一个 C ++ 14-时尚变量模板:

You might like to add a C++14-fashion variable template:

template <typename T, typename... Ts>
constexpr std::size_t Index_v = Index<T, Ts...>::value;

DEMO

这篇关于如何获取变量类型包中的类型的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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