Reputation: 311
I have two Classes TreeNodeRange(Tree & t)
and VertexNodeRange(Vertex & v)
. Looping over the first is equal to looping over all nodes in a tree whereas looping over the second is equal to looping over all nodes that a children to a given vertex v.
Now depending on user input I would like to either loop over the whole tree or only the subtree that starts at v.
I tried something like this:
const bool only_subtree = to_bool(argv[1]);
typedef std::conditional<only_subtree, VertexNodeRange,TreeNodeRange>::type NodeRange;
The problem is now that I don't see how I can define an object of type NodeRange. I tried:
Vertex v = tree.get_vertex_by_id(17);
NodeRange get_range = [&](const bool only_subtree, Vertex & v)
{
if(only_subtree) return NodeRange(v);
return NodeRange(tree);
};
for(auto node : get_range(only_subtree, v)){
...
}
The compiler doesn't seem to like this since the constructor NodeRange must be callable with either Vertex or Tree which of course it does not.
It there a way to do this in C++ at all?
Cheers
Upvotes: 0
Views: 322
Reputation: 176
You can make a template function:
template<typename AnyNodeRange>
void processChildNodes(AnyNodeRange& anyNodeRange)
{
for(auto node : anyNodeRange){
...
}
}
and use it like this :
Vertex v = tree.get_vertex_by_id(17);
if (only_subtree) {
VertexNodeRange vertexNodeRange(v);
processChildNodes(vertexNodeRange);
}
else
{
TreeNodeRange treeNodeRange(tree);
processChildNodes(treeNodeRange);
}
You cannot make typedefs using only_subtree, because it is user input, only known at runtime, where as types are only defined at compilation time.
Upvotes: 2