【问题标题】:How to get the index of a type in a variadic type pack?如何获取可变参数类型包中类型的索引?
【发布时间】:2014-11-27 22:28:38
【问题描述】:

例如

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

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

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

【问题讨论】:

标签: c++ c++11 variadic-templates


【解决方案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> {};

您可能想添加一个 变量模板:

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

DEMO

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 2015-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多