Boost logo

Boost :

From: Dave Vasilevsky (gridd_at_[hidden])
Date: 2001-08-07 00:01:52


I've been trying to use boost::any in one of my projects, but I keep running up
against a problem: Templates and boost::any don't work together the way I'd
like them to.

Here's what I mean. Code like the following is a trivial example of what
templates are all about.

std::list<int> myList;
std::vector<int> myVec;

std::back_inserter(myList) = 1;
std::back_inserter(myVec) = 1;

Although it's a pretty useless example, this shows templates operating on two
classes with the same interface. What I'd really love to be able to do is
something like this:

boost::any stl_container;

if ( vector_is_optimal() )
   stl_container = std::vector<int>();
   stl_container = std::list<int>();

std::back_inserter( stl_container ) = 1;

However, this won't work, since any doesn't have a push_back() method.
Equally good though, would be the ability to use the visitor idiom with any:

class any {
   template <typename UnaryFunctor>
   UnaryFunctor::Result visit(UnaryFunctor& f) { contents->visit(f); }
   class placeholder {
      template <typename UnaryFunctor>
      virtual UnaryFunctor::Result visit(UnaryFunctor& f) = 0;
   /* etc */

But this doesn't work either, since virtual methods can't be templated. So my
question: is there a way to implement the visitor idiom with any, or a
modified version thereof? Using just virtual methods, one could easily
implement a push_back() operation for any; but a new method must be added to
the definition of any every time one wants to add another operation. Is there a
general solution?

Thanks for your help,


Boost list run by bdawes at, gregod at, cpdaniel at, john at