gpt4 book ai didi

C++14 将元组三乘三展开

转载 作者:行者123 更新时间:2023-12-02 05:54:50 25 4
gpt4 key购买 nike

我有一个大小为 3 倍数的 C++14 元组,我想将其按顺序 3 × 3 扩展为一个函数。

tuple<int, int, int, int, int, int> a(1, 2, 4, 6, 7, 2);

void process_triplet(int& mystate, int a, int b, int c) {
// do something on a b c and mystate
}

template <typename Tuple>
void process_triplets(Tuple&& tuple) {
// how do I write over here such that I can 'sequentially' processing each triplet
// ideally I want the following:
// process_triplet(mystate, 1, 2, 3);
// process_triplet(mystate, 4, 5, 6);
}

需要帮助以通用方式实现process_triplets

最佳答案

好吧,你需要一个 std::index_sequencepack-expansion :

template <class Tuple, std::size_t... N>
void process_triplets_impl(int& mystate, Tuple&& tuple, std::index_sequence<N...>) {
int x[] = {
0,
((void)process_triplet(
mystate,
std::get<N * 3 + 0>(std::forward<Tuple>(tuple)),
std::get<N * 3 + 1>(std::forward<Tuple>(tuple)),
std::get<N * 3 + 2>(std::forward<Tuple>(tuple))
), 0)
...
};
(void)x;
}
template <class Tuple>
void process_triplets(int& mystate, Tuple&& tuple) {
process_triplets_impl(
mystate
std::forward<Tuple>(tuple),
std::make_index_sequence<std::tuple_size<std::decay_t<Tuple>>::value / 3>()
);
}

关于C++14 将元组三乘三展开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59187445/

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