C++17 有效地将参数包参数与 std::array 元素相乘

c++17 efficiently multiply parameter pack arguments with std::array elements

本文关键字:参数 std array 元素 有效地 包参数 C++17      更新时间:2023-10-16

我想有效地将参数包中的参数与 std::array 的元素相乘:

int index(auto... Is, std::array<int,sizeof...(Is)> strides)
{
// pseudo-code
// int idx = 0;
// for(int i = 0; i < sizeof...(Is); ++i)
//   idx += Is[i] * strides[i];
// return idx; 
}

我无法完全理解这个问题。我开始走索引序列的道路,但我可以弄清楚如何合并求和。

我使用的是 c++17,所以折叠表达式如果能简化代码,那就是公平的游戏。

感谢您的任何指示。

编辑:澄清了伪代码。唯一的伪部分是表达式Is[i],它引用第 i 个参数包参数。

T.C. 下面的答案是完美的,这是我的最终代码,它是一个成员函数:

unsigned int index(auto... indexes)
{
unsigned int idx = 0, i = 0;
(..., (idx += indexes * m_strides[i++]));
return idx;
}

在撰写本文时,代码使用 gcc 6.3.0 和 -fconcepts 标志进行编译,该标志引入了概念 TS。

使用auto... indexestemplate<typename Args> f(Args... indexes)的简写。我试图使用一个无符号的 int 概念作为参数,但我无法让它工作。

(...,) 折叠是关键元素,并扩展到类似的东西(如果你实际上可以 [] 到参数包中):

idx += indexes[0] * m_strides[i++], idx += indexes[1] * m_strides[i++], etc.

这就是我所缺少的洞察力。

我无法auto...工作,所以我更改了index的签名。

你需要一个辅助函数(index_helper这里)来使用index_sequence,因为它依赖于模板参数推导来填充索引。

#include <array>
#include <cstdio>
template <typename... T, size_t... i>
//                       ^~~~~~~~~~~
//                        use deduction to make {i...} = {0, 1, 2, ..., n}
static int index_helper(const std::array<int, sizeof...(T)>& strides,
std::index_sequence<i...>,
T... Is) 
{
return (0 + ... + (strides[i] * Is));
}
template <typename... T>
int index(const std::array<int, sizeof...(T)>& strides, T... Is) {
return index_helper(strides, std::make_index_sequence<sizeof...(T)>(), Is...);
//                               ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                                generates {0, 1, 2, ..., n}
}
int main() {
printf("%dn", index({1, 100, 100000, 1000}, 2, 3, 5, 7));
// 507302
}

如果你能把参数包敲定成一个复制/移动成本低的单一类型,你可以把它变成一个数组:

T arr[] = { static_cast<T>(Is)... }; // for some T, possibly common_type_t<decltype(Is)...>

然后,您可以将伪代码转换为真实代码。

如果这不可行,可以使用逗号折叠:

int idx = 0, i = 0;
(..., (idx += Is * strides[i++]));
return idx;