gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-27 23:58:27 27 4
gpt4 key购买 nike

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

// 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com