该模板如何工作以查找元组的索引?

时间:2016-11-28 12:04:38

标签: c++ templates tuples template-meta-programming

在我的项目中,有一个由模板定义的函数来查找元组的索引,我还是不明白它是如何工作的: 似乎有一个递归,但我不知道它是如何终止在正确的索引?

    .schedule {
    	position: relative;
    	padding-bottom: 56.25%; /* 16:9 */
    	padding-top: 25px;
    	height: 0;
    }
    .schedule iframe {
    	position: absolute;
    	top: 0;
    	left: 0;
    	width: 100%;
    	height: 100%;
    }

1 个答案:

答案 0 :(得分:3)

专业化是终止条件。请注意,它要求First等于Search

type_index<Index, Search, Search, Types ...>
                  ^^^^^^  ^^^^^^

例如,如果您从

开始
type_index<0, C, A, B, C, D>,

这不符合专业化,因此将使用通用模板,重定向(通过其type成员)

type_index<0, C, A, B, C, D>::type = type_index<1, C, B, C, D>::type

但是直到链到达

才能评估
type_index<0, C, A, B, C, D>::type = ... = type_index<2, C, C, D>::type

此时可以使用部分特化,即

type_index<2, C, C, D>::type = type_index<2, C, C, D>
type_index<2, C, C, D>::index = 2

等等

type_index<0, C, A, B, C, D>::type::index = 2
                 ^  ^  ^  ^
                 0  1  2  3

按预期。

请注意,您无需携带Index,确实可以删除整个::type内容:

template<typename, typename...>
struct type_index;

template<typename Search, typename Head, typename... Tail>
struct type_index<Search, Head, Tail...> {
  // Search ≠ Head: try with others, adding 1 to the result
  static constexpr size_t index = 1 + type_index<Search, Tail...>::index;
};

template<typename Search, typename... Others>
struct type_index<Search, Search, Others...> {
  // Search = Head: if we're called directly, the index is 0,
  // otherwise the 1 + 1 + ... will do the trick
  static constexpr size_t index = 0;
};

template<typename Search>
struct type_index<Search> {
  // Not found: let the compiler conveniently say "there's no index".
};

这适用于:

type_index<C, A, B, C, D>::index
  = 1 + type_index<C, B, C, D>::index
  = 1 + 1 + type_index<C, C, D>::index
  = 1 + 1 + 0
  = 2

如果类型不在列表中,则会说(GCC 6.2.1):

In instantiation of ‘constexpr const size_t type_index<X, C>::index’:
  recursively required from ‘constexpr const size_t type_index<X, B, C>::index’
  required from ‘constexpr const size_t type_index<X, A, B, C>::index’
  required from [somewhere]
error: ‘index’ is not a member of ‘type_index<X>’

我觉得很清楚。