【问题标题】:Template for loops in C++C++中的循环模板
【发布时间】:2020-02-26 12:30:37
【问题描述】:

有没有办法拥有可以处理 n(变量)嵌套循环的相同模板?

例如:

for (auto & node : mnodes) {
    for (auto & parent : node->parents) {
        \\ do something
   }
}
for (auto & tree : mtrees) {
    for (auto & branch : tree->mbranches) {
         for(auto & root : branch ->roots  ) {
             \\ do something
       }
   }
}

外循环和内循环的参数总是不同的,内循环的数量也不同。

【问题讨论】:

  • 请更具体一些。您想在编译时选择哪些参数在运行时选择什么?总是parentschildrenvalues 还是不同的成员?顺便说一句,“有办法吗?”总是“是”。你尝试过什么吗?您能否展示一些代码来说明该模板的外观或您希望如何使用它?
  • 你想递归地下降嵌套模板还是指针树。两种不同的东西?一个是(例如)std::vector<:vector>>>,另一个只是一个可以探索的节点树在运行时使用树遍历。
  • C++20 的协程或范围在这方面可能会有所帮助。链接转换或选择器函数。
  • 前段时间我问了一个类似的问题。答案很有启发性。 stackoverflow.com/questions/59964594/…
  • @HazemAbaza 您能否提供您希望迭代的类的完整实现。例如,孩子也是节点吗?孩子也有自己的孩子,他们有自己的孩子。您需要向我们展示定义和类型。

标签: c++ templates


【解决方案1】:

您可以使用一组可变参数的函数(类似),然后遍历除最后一个之外的所有函数。

template <typename T, typename Last>
void nested_foreach(T&& t, Last&& last) {
     std::forward<Last>(last)(std::forward<T>(t));
}

template <typename T, typename First, typename Second, typename... Rest>
void nested_foreach(T & t, First&& first, Second&& second, Rest&& rest) {
    for (auto&& u : std::forward<First>(first)(std::forward<T>(t))) {
        nested_foreach(std::forward<decltype(u)>(u), std::forward<Second>(second), std::forward<Rest>(rest)...);
    }
}

你会使用喜欢的:

nested_foreach(mnodes, std::mem_fn(&Node::parents), [](auto &){ /* do something */ });

nested_foreach(mtrees, std::mem_fn(&Tree::mbranches), std::mem_fn(&Branch::roots), [](auto &){ /* do something */ });

【讨论】:

    【解决方案2】:

    我认为模板方法太复杂了。我会在分离的函数中移动变量逻辑

    void do_something_parents(const Node &node) {
        for (auto & parent : node->parents) {
            \\ do sthg
       }
    }
    
    void do_something_children(const Node &node) {
        for (auto & child : node->children) {
            for(auto & value : node ->values  ) {
             \\ do sthg
            }
        }
    }
    

    然后,您可以将它们用作

    for (auto & node : mnodes) {
        do_something_parents(node);
        do_something_children(node);
    }
    

    【讨论】:

    • 如果子节点也是拥有自己子节点的节点等等,这将不起作用。然而,OP 并没有真正提供足够的信息。
    猜你喜欢
    • 2021-08-28
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    • 1970-01-01
    • 1970-01-01
    • 2012-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多