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

标签 c++ tuples c++14 metaprogramming

我有一个大小为 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/

相关文章:

c++ - g++-Python.h : No such file or directory

python - 从列表中的每个键获取具有最大值的元组

c++ - 将元组传递给辅助类

python - Python 的列表、元组和字典的 Node.js 等效数据类型

c++ - 我们能否在可能的情况下使用返回值优化,而在可能的情况下退回到移动而不是复制语义?

c++ - 将 Boost multi_index 用于组合键

c++ - std::make_shared 与 std::initializer_list

c++ - 获取停靠 MFC CDockablePane 的停靠区域

c++ - 原始套接字的 udp 数据包碎片

c++ - 为什么 "auto ch = unsigned char{' p'}"在 C++ 17 下不能编译?