Boost logo

Boost Users :

From: Matthew Jankowski (mattjankowski_at_[hidden])
Date: 2005-01-07 15:07:14


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. For example, if I insert 3 Base* pointers
and 2 DerivedBase* pointers, I need to be able to extract the 3 Base *
pointers and the 2 DerivedBase* pointers at a later point in time. To this
end, class Base* has another member function 'template< typename C> int
numPointer( C * InPointer)' which is intended to count the number of
pointers found in the container.

template< typename C> int numPointer(C* InPointer) has a few problems: 1)
typeid(Pointers[i]) returns the 'variant' typeid when I really need to know
the typeid of the ith pointer in 'Pointers'. 2) There must be a better, more
elegant (and safe) way to make use of the boost library to accomplish just
what I want.

int main() {

    Base * TempBase = new Base();

    DerivedBase * TempDeri = new DerivedBase();

    TempBase->insert(TempBase);

    TempBase->insert(TempBase);

    TempBase->insert(TempDeri);

    std::cout << "Base:" << TempBase->numPointer(TempBase) << endl;
//Expect "Base:2" get "Base:0" because of typeid().

   std::cout << "Deri:" << TempBase->numPointer(TempDeri) << endl; //Expect
"Deri:1" get "Deri:0" because of typeid().

}

 

class Base {

private:

vector<boost::variant <Base*, DerivedBase*> > Pointers;

public:

Base();

virtual ~Base();

template <typename C> void insert( C * inC )

{

Pointers.push_back(inC);

}

template <typename C> int numPointer( C* inC ) {

int counter(0);

for ( int i(0); i < int(Pointers.size()); i++ ) {

cout << "type:" << typeid(inC).name() << endl;

cout << "typeP:" << typeid(Pointers[i]).name() << endl; //Will give the id
of the container not Pointer[i].

//if( boost::is_same<Pointers[i],typeid(inC).name()>::value ){ //Compilation
error

if ( typeid(inC).name() == typeid(Pointers[i]).name() ) {

counter++;

}

}

return counter;

}

}; //Base

 

Any advice on how to improve this code and/or make better use of the boost
library is fully appreciated.

Thanks,

Matt

 



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net