Skip to content

Instantly share code, notes, and snippets.

@matovitch
Created May 14, 2019 14:56
Show Gist options
  • Save matovitch/145d837d455c64c9c1775e68f6f4d508 to your computer and use it in GitHub Desktop.
Save matovitch/145d837d455c64c9c1775e68f6f4d508 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <cstdint>
#include <vector>
namespace tree
{
template <class Type>
struct TNode
{
template <class... Args>
TNode(const std::size_t theSize, Args&&... args) :
size {theSize},
value {args...}
{}
std::size_t size;
Type value;
};
template <class Type>
std::ostream& operator<<(std::ostream& os, const TNode<Type>& node)
{
return os << '(' << node.value << ", " << node.size << ')';
}
} // namespace tree
template <class Type>
class TTree
{
using Node = tree::TNode<Type>;
public:
std::size_t size() const
{
return _nodes.size();
}
template <class... Args>
void addNode(const std::size_t theSize, Args&&... args)
{
_nodes.emplace_back(size() - theSize, args...);
}
const std::vector<Node>& nodes() const
{
return _nodes;
}
private:
std::vector<Node> _nodes;
};
template <class Type>
std::ostream& operator<<(std::ostream& os, const TTree<Type>& tree)
{
for (const auto& node : tree.nodes())
{
os << node;
}
return os;
}
namespace tree
{
template <class Type>
class TBuilder
{
using Tree = TTree <Type>;
using Builder = TBuilder <Type>;
public:
TBuilder(Tree& tree) : _tree{tree} {}
TBuilder(const Builder& builder) :
_tree{builder._tree },
_size{builder._tree.size() }
{}
template <class... Args>
void build(Args&&... args)
{
_tree.addNode(_size, args...);
}
private:
Tree& _tree;
std::size_t _size;
};
} // namespace tree
using Tree = TTree <char>;
using TreeBuilder = tree::TBuilder <char>;
void addLeaf(const char value, TreeBuilder treeBuilder)
{
treeBuilder.build(value);
}
void makeMyTree(TreeBuilder treeBuilder)
{
addLeaf('a', treeBuilder);
addLeaf('b', treeBuilder);
treeBuilder.build('c');
}
int main()
{
Tree tree;
TreeBuilder treeBuilder{tree};
makeMyTree(treeBuilder);
std::cout << tree << '\n';
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment