gpt4 book ai didi

c++ - 如何基于元组元素进行递归?

转载 作者:行者123 更新时间:2023-12-02 09:53:19 25 4
gpt4 key购买 nike

我不确定是否可行,但是我希望能够基于元组的元素递归调用函数。因此,例如std::tuple<int,float,double>之类的元组应调用expand_nested 3次,然后依次使用intfloatdouble类型的参数调用其回调函数。

#include <tuple>
#include <vector>
#include <functional>

template <typename T>
struct tree_item
{
T param;
std::function<void(T)> callback;
};

template <typename... Ts>
struct tuple_node
{
std::tuple<Ts...> tupl;
};

// recursion base case
template <typename T>
void expand_nested(tree_item<T> ti)
{
ti.callback(ti.param);
}

// recursive function
template <typename T>
void expand_nested(tree_item<T> ti, tree_item<T> rest...)
{
ti.callback(ti.param);
expand_nested(ti, rest...);
}

template <typename... Ts>
void expand_root(tuple_node<Ts...> nodes)
{
auto current = std::get<1>(nodes.tupl);
auto rest = std::get<...>(nodes.tupl); // Made up syntax that doesn't work
// How can I fill the "rest" variable with the remaining elements of the "nodes.tupl" tuple?

expand_nested(current, rest...);
}

int main()
{
tuple_node<tree_item<int>, tree_item<float>> nodes;

tree_item<int> tree_int;
tree_item<float> tree_float;
tree_item<double> tree_double;

tuple_node<tree_item<int>, tree_item<float>, tree_item<double>> node;
node.tupl = std::make_tuple(tree_int, tree_float, tree_double);

expand_root(nodes);
}

最佳答案

expand_nested中的参数pack的语法应为:

template <typename T, typename ... Rest>
void expand_nested(tree_item<T> ti, tree_item<Rest>... rest)
这个
ti.callback(ti.param);
expand_nested(ti, rest...);
将为您提供无限递归(您要在第一次调用时使用相同数量的参数来调用相同的函数),其外观应类似于:
template <typename T, typename ... Rest>
void expand_nested(tree_item<T> ti, tree_item<Rest>... rest)
{
ti.callback(ti.param); // process ti
expand_nested(rest...); // don't pass ti, pass only the rest to further processing
}
从C++ 17开始,有一种简单的方法可以提取元组的所有元素-使用 std::apply:
template <typename... Ts>
void expand_root(tuple_node<Ts...> nodes)
{
std::apply([](auto&... tupleItems){
expand_nested(tupleItems...); }, nodes.tupl);
}
Full demo

关于c++ - 如何基于元组元素进行递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62489769/

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