$include_dir="/home/hyper-archives/boost-users/include"; include("$include_dir/msg-header.inc") ?>
From: Caleb Epstein (caleb.epstein_at_[hidden])
Date: 2005-01-09 23:30:19
On Fri, 7 Jan 2005 14:07:14 -0600, Matthew Jankowski
<mattjankowski_at_[hidden]> wrote:
>  
> 
> Hi all, I'm new to Boost and have some questions about how to get data out
> of a vector<boost::variant<> > container. For this purpose I put together
> 'class Base' which holds a vector<boost::variant <Base*, DerivedBase*> >
> Pointers. I wrote a function template to insert pointers, but I have real
> difficulty extracting pointers.
I'm not sure what you're trying to do makes much sense to do with
Boost.Variant.  It is more suited to storing objects than pointers.
Why not just a std::vector<boost::shared_ptr<Base> >>?  I'm assuming
your DerivedBase object inherits from Base and you're trying to avoid
slicing by storing pointers in your container.
If you're insistent on using Variant, you can use get<T> to pull out a
value by its type:
#include <vector> 
#include <iostream> 
#include <algorithm> 
 
#include <boost/variant.hpp> 
 
using namespace std; 
using namespace boost; 
 
struct base {}; 
struct derived : public base {}; 
 
typedef variant<base*, derived*> holder; 
 
struct is_base { 
    bool operator () (holder& h) const { 
        return get<base*> (&h) != 0; 
    } 
}; 
 
struct is_derived { 
    bool operator () (holder& h) const { 
        return get<derived*> (&h) != 0; 
    } 
}; 
 
int 
main () 
{ 
    vector<holder> geoffrey; 
    geoffrey.push_back (new base); 
    geoffrey.push_back (new base); 
    geoffrey.push_back (new base); 
    geoffrey.push_back (new derived); 
    geoffrey.push_back (new derived); 
 
    cout << "base: " << count_if (geoffrey.begin (), geoffrey.end (), 
                                  is_base ()) 
         << ", derived: " << count_if (geoffrey.begin (), geoffrey.end (), 
                                       is_derived ()) 
         << endl; 
} 
 
-- Caleb Epstein caleb dot epstein at gmail dot com