有人可以解释一下"indices trick"吗?
Can someone please explain the "indices trick"?
我注意到在美观打印元组的上下文中提到了"索引技巧"。听起来很有趣,所以我按了链接。
嗯,那不太顺利。我明白了这个问题,但真的不明白是怎么回事。为什么我们需要指标呢?这里定义的不同函数对我们有什么帮助?什么是"裸"?等。
谁能给那些不太懂参数包和可变元组的人详细介绍一下吗?
问题是:我们有一个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_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>(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;
相关文章:
- 有人能分解一下这个c++模板的语法吗
- 有人能解释一下为什么下界是这样工作的吗C++的
- 我是c ++的新手,你能解释一下在这种情况下的指针吗
- 有人能为我解释一下C++代码吗
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 你能解释一下什么运行时错误是如何解决它的吗?
- 有人可以解释一下这段代码如何能够反转字符串
- 解释一下 for (char c : str) 的作用?
- 有人可以解释一下这个矩阵幂函数是如何工作的吗?
- 有人可以向我解释一下这段代码的作用吗?
- 任何人都可以解释一下我是否需要 & 在第一个代码片段中
- 我不完全确定此代码的行为.有人可以向我解释一下吗?
- 有人可以解释一下吗?这是关于数组和数组内部 if 语句的一些处理
- 请描述一下在 c++ 中在此类中定义构造函数的方式?
- 我无法理解这一点,有人可以帮我解释一下吗?
- 有人可以解释一下复制功能的作用吗?
- 解释一下这个排序算法是如何工作的?
- 我在 2D 数组的动态内存分配中遇到了一些奇怪的代码C++? 请解释一下这是什么?
- 有人能给我解释一下下面的模板代码吗
- 有人可以解释一下"indices trick"吗?