有人可以解释一下"indices trick"吗?

Can someone please explain the "indices trick"?

本文关键字:一下 indices trick 解释      更新时间:2023-10-16

我注意到在美观打印元组的上下文中提到了"索引技巧"。听起来很有趣,所以我按了链接。

嗯,那不太顺利。我明白了这个问题,但真的不明白是怎么回事。为什么我们需要指标呢?这里定义的不同函数对我们有什么帮助?什么是"裸"?等。

谁能给那些不太懂参数包和可变元组的人详细介绍一下吗?

问题是:我们有一个std::tuple<T1, T2, ...>,我们有一些函数f,我们可以调用每个元素,其中f返回一个int,我们希望将这些结果存储在一个数组中。

让我们从一个具体的例子开始:

template <typename T> int f(T ) { return sizeof(T); }
std::tuple<int, char, double> tup{42, 'x', 3.14};
std::array<int, 3> arr{ f(std::get<0>(tup)), 
                        f(std::get<1>(tup)),
                        f(std::get<2>(tup)) );

除了写出所有的get s在最好的情况下是不方便和冗余的,在最坏的情况下是容易出错的。

首先,我们需要包含std::index_sequencestd::make_index_sequence的实用程序头文件:

#include <utility>

现在,假设我们有一个类型index_sequence<0, 1, 2>。我们可以使用它将数组初始化折叠成可变的包展开:

template <typename Tuple, size_t... Indices>
std::array<int, sizeof...(Indices)> 
call_f_detail(Tuple& tuple, std::index_sequence<Indices...> ) {
    return { f(std::get<Indices>(tuple))... };
}

这是因为在函数中,f(std::get<Indices>(tuple))...被扩展为f(std::get<0>(tuple)), f(std::get<1>(tuple)), f(std::get<2>(tuple))。这正是我们想要的。

问题的最后一个细节就是生成特定的索引序列。c++ 14实际上给了我们这样一个名为make_index_sequence

的实用程序
template <typename Tuple>
std::array<int, std::tuple_size<Tuple>::value>
call_f(Tuple& tuple) {
    return call_f_detail(tuple,
        // make the sequence type sequence<0, 1, 2, ..., N-1>
        std::make_index_sequence<std::tuple_size<Tuple>::value>{}
        );
}

,而您链接的文章只是解释了如何实现这样的元函数。

Bare可能是类似的,从Luc Danton的回答:

template<typename T>
using Bare = typename std::remove_cv<typename std::remove_reference<T>::type>::type;