c++ - 这个模板如何找到元组的索引?

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

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

// retrieve the index (for std::get) of a tuple by type
//  usage: std::get<Analysis::type_index<0, Type, Types ...>::type::index>(tuple)
//  TODO: should make this tidier to use
template<int Index, class Search, class First, class ... Types>
struct type_index
{
  typedef typename Analysis::type_index<Index + 1, Search, Types ...>::type type;
  static constexpr int index = Index;
};

template<int Index, class Search, class ... Types>
struct type_index<Index, Search, Search, Types ...>
{
  typedef type_index type;
  static constexpr int index = Index;
};

最佳答案

特化是终止条件。请注意,它要求 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>’

我觉得这是不言自明的。

关于c++ - 这个模板如何找到元组的索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40843868/

相关文章:

c++ - 访问 std::string 中的空终止符(字符串下标超出范围)

c++ - 缩写函数模板与带有转发引用参数的函数模板

c++ - 在模板特化中添加单个构造函数方法

python - 高效搜索二元组

python - 对运算符表达式的结果调用函数? (掩码==instance_id).astype(np.uint8)

C++: glfw3 on ubuntu undefined reference

c++ - CGAL,限制在矩形中的裁剪 voronoi 图

c++ - 根据可散列的模板使用正确的容器类型

javascript - 模板中的 Bigcommerce 购物车内容

python - 在for循环python中打印元组