其他分享
首页 > 其他分享> > c – 有人可以解释“指数技巧”吗?

c – 有人可以解释“指数技巧”吗?

作者:互联网

我注意到在精美打印元组的上下文中提到了“索引技巧”.这听起来很有趣,所以我跟着the link.

嗯,那不顺利.我理解了这个问题,但实际上并不能跟踪发生的事情.为什么我们甚至需要任何指数?那里定义的不同功能如何帮助我们?什么是’裸露’?等等

有人可以为参数包和可变元组的专家提供那种东西的游戏吗?

解决方法:

问题是:我们有一个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)) );

除了写出所有那些获取是不方便和冗余充其量,最坏的情况下容易出错.

首先,我们需要为std :: index_sequence和std :: 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>(元组) )),f(std :: get< 2>(元组)).这正是我们想要的.

问题的最后一个细节就是生成特定的索引序列. 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>{}
        );
}

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

Luc Danton’s answer开始,裸露可能就像是:

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

标签:indices,c,c11,tuples,variadic-templates
来源: https://codeday.me/bug/20190923/1815804.html