Question

In Java, I am able to define a variable of a generic class without specifying type.

class Tree<T extends Comparable<? super T>> {}
somewhere-else: Tree tree;

I can then read in some object from a file and type-cast it to the class type I desire.

tree = (Tree<String>) some object;

With boost::variant I have begun a variant definition.

typedef boost::variant<Tree<std::string>, Tree<int>> TreeVariant; TreeVariant tree;

I know I need to specify a visitor class but it is not clear from this example how to define it such that I am able to assign to my tree variable either Tree<std::string> or Tree<int>.

I would then like to proceed from there to call member functions of Tree using the variable tree.

Was it helpful?

Solution

There is no need to create a visitor for assigning values to a boost::variant. As shown in the Basic Usage section of the tutorial, you just assign the value:

TreeVariant tree;
Tree<std::string> stringTree;
Tree<int> intTree;
tree = stringTree;
tree = intTree;

As for calling member functions, you should use a visitor:

class TreeVisitor : public boost::static_visitor<>
{
public:
  void operator()(Tree<std::string>& tree) const
  {
    // Do something with the string tree
  }

  void operator()(Tree<int>& tree) const
  {
    // Do something with the int tree
  }
};

boost::apply_visitor(TreeVisitor(), tree);

You can also return values from a static_visitor, like so:

class TreeVisitor : public boost::static_visitor<bool>
{
public:
  bool operator()(Tree<std::string>& tree) const
  {
    // Do something with the string tree
    return true;
  }

  bool operator()(Tree<int>& tree) const
  {
    // Do something with the int tree
    return false;
  }
};

bool result = boost::apply_visitor(TreeVisitor(), tree);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top