construct trees with TreeNode<T> instead of T

This allows constructing some subtrees imperatively, instead of having
to construct everything declaratively. Consider we want to construct the
following tree:

Fans|
    |0|Read
    | |Write
    |
    |1|Read
      |Write

The leaf nodes might be hard to construct declaratively, since they can't easily know
which fan index they should use, since they only get the amount of fans.
This commit is contained in:
Jussi Kuokkanen 2023-09-30 16:09:10 +03:00
parent d0adac6b47
commit fc86b22ac5

View File

@ -4,9 +4,9 @@
#include <Tree.hpp>
// Allows declarative and conditional tree construction
// More precisely, TreeConstructor a b -> TreeNode b, where there is a function a -> [b]
// More precisely, TreeConstructor a b -> TreeNode b, where there is a function a -> [TreeNode b]
template <typename In, typename Out> struct TreeConstructor {
std::function<std::vector<Out>(In)> nodesToAttach;
std::function<std::vector<TuxClocker::TreeNode<Out>>(In)> nodesToAttach;
std::vector<TreeConstructor<In, Out>> children;
};
@ -14,8 +14,7 @@ template <typename In, typename Out>
void constructTree(TreeConstructor<In, Out> consNode, TuxClocker::TreeNode<Out> &node, In in) {
for (auto &newNode : consNode.nodesToAttach(in)) {
// Attach wanted child
auto treeNode = TuxClocker::TreeNode<Out>{newNode};
node.appendChild(treeNode);
node.appendChild(newNode);
for (auto &child : consNode.children)
// We need pointer since node.children() just gives a copy
constructTree(child, node.childrenPtr()->back(), in);