Boost logo

Boost Users :

From: Matt S Trentini (matt_s_trentini_at_[hidden])
Date: 2003-11-27 03:51:28


Heya Everyone,

I am trying to create a generic way to extract a list of objects from
another list of objects. Let me explain!

Say I have a vector (or any container with fwd iterators and value_type)
that contains objects that have a function which returns a long (could
actually be any type). I want to iterate over that vector and extract
each of the longs into a list (or any container that supports push_back
and defines value_type). Something like the following:

     class HandleClass
     {
     public:
         long handle() const { return val_++; }
     private:
         static long val_;
     };

     // ...

     std::vector<HandleClass> listOfHcs;

     // ... fill listOfHcs here

     std::list<long> needToFill;

OK so far. I then wrote this extraction function (yes, there are many
ways I could have done this - with a functor and using foreach is
another possibility worth exploring, but not now :) ).

     template
     <
         class ReturnContainer,
         class FwdIterator
>
     void Extract(const FwdIterator & itBegin,
                  const FwdIterator & itEnd,
                  ReturnContainer & container,
                  boost::function1<ReturnContainer::value_type,
FwdIterator::value_type> f)
     {
         for (FwdIterator it = itBegin ;it != itEnd; ++it)
         {
             container.push_back(f(*it));
         }
     };

And I was able to do this:

     Extract(listOfHcs.begin(), listOfHcs.end(), needToFill,
&HandleClass::handle);

And it worked like a charm. needToFill gets filled and I was happy. :)

However we also had containers of _pointers_to_ HandleClasses. So in
some cases our vector looked like:

     std::vector<HandleClass *> listOfHcs;

Yet the same code worked! I couldn't, and can't, for the life of me
understand what was going on (I expected that I would have to wrap the
(*it) in a boost::remove_pointer which worried me because my compiler -
MSVC7.0 - doesn't support partial template specialization). Don't get
me wrong, I'm happy that it work but can anyone explain what
fandangelory is going on inside boost::function (or perhaps it's some
C++ magic?) to allow this?

Cheers,
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