lundi 31 juillet 2017

C++ variable type conditional

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

Aucun commentaire:

Enregistrer un commentaire