Boost logo

Boost Users :

Subject: [Boost-users] [Range] Adapt 2-iterator container constructors for Range?
From: Nat Goodspeed (nat_at_[hidden])
Date: 2008-09-23 22:29:09


As I work with Boost.Range, I frequently want to call a method returning
an iterator_range and, from that range, instantiate a standard
container. I have a couple of helpers I'd like to propose for inclusion
in the Boost.Range library.

/**
  * From any range compatible with Boost.Range, return an instance of any
  * class with a constructor accepting a compatible iterator pair.
  */
template<class TYPE, typename RANGE>
TYPE make_from_range(const RANGE& range)
{
     return TYPE(boost::begin(range), boost::end(range));
}

It would probably be appropriate to provide a non-const RANGE& overload
as well.

make_from_range<CONTAINER>(range) is helpful for, e.g., passing an
argument to a function accepting const CONTAINER&. But what if you want
to declare a local instance of such a container?

/**
  * From any range compatible with Boost.Range, instantiate any class
  * with a constructor accepting a compatible iterator pair.
  */
template<class TYPE>
struct instance_from_range: public TYPE
{
     template<typename RANGE>
     instance_from_range(const RANGE& range):
         TYPE(boost::begin(range), boost::end(range))
     {}
     // Again, a non-const RANGE& overload would probably be useful.
};

Usage example:

instance_from_range< std::vector<std::string> >
     my_vector(function_returning_range_of_string());

Perhaps instance_from_range might be more controversial because of the
recommendation not to subclass standard containers. My thought is that
once the (nearly trivial) constructor has executed, we can completely
disregard the subclass. I've used it in a context where
instance_from_range<CONTAINER> is "sliced" to the CONTAINER itself.

Though these are small enough to recreate on demand, they're useful
enough that I'd like to have them available everywhere. I hope others
might find them helpful too.


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