Boost logo

Boost :

Subject: Re: [boost] Interest in a container which can hold multiple data types?
From: Thijs (M.A.) van den Berg (thijs_at_[hidden])
Date: 2015-05-04 14:50:19


> On 04 May 2015, at 18:51, Boris Rasin <boris_at_[hidden]> wrote:
>
>> On 5/4/2015 6:33 PM, James Armstrong wrote:
>> The main difference between this and a container of boost:any is that the
>> container of boost::any still is a container of one data type, just being
>> that one data type is a very flexible one. This container natively
>> supports insertion of different data types. So, you could do,
>>
>> int my_int = 5;
>> double my_double0 = 9342.132;
>> double my_double1 = 987.654;
>> std::string my_string("This is a string.");
>> std::vector<double> my_vec;
>> my_vector.push_back(123.456);
>>
>> omni my_container;
>>
>> my_container.push_back(my_int);
>> my_container.push_back(my_double);
>> my_container.push_back(my_string);
>> my_container.push_back(my_vector);
>>
>> and the container happily stores the data.
>
> This also works with std::vector<boost::any>.
>
>> You can then access the data through iterators
>>
>> //access all doubles
>> for (auto itr = my_container.begin<double>(); itr !=
>> my_containert.end<double>(); ++itr)
>> {
>> std::cout << *itr << std::endl;
>> }
>>
>> or through specifying the data type and index
>>
>> //get the 0th element string
>> std::cout << my_container.at<string>(0) << std::endl;
>
> This could be useful, but wouldn't it be better to write this as generic algorithms capable of working with any container of boost::any, not just vector? Better yet, any container of type erased objects (boost::any, boost::variant, etc.) using something like boost::get<T>()?
>

I would actually prefer not to use type erasure: make a strong-typed and efficient heterogenous container. Something like this... ?

template <typename... Args>
struct tuple_vector : std::tuple< std::vector<Args>... >
{
   typename std::tuple<Args...> type;

   template <typename T>
   void push_back(const T& value)
   { std::get< std::vector<T> >(*this).push_back(value); }

   template <typename T>
   void push_back( T&& value)
   { std::get< std::vector<T> >(*this).push_back(value); }
};

struct Point {
   double x;
   double y;
};
struct Line {
   double x;
   double y;
   double a;
   double l;
};
struct Rectangle {
   double x;
   double y;
   double a;
   double w;
   double h;
};
struct Circle {
   double x;
   double y;
   double r;
};

tuple_vector<Point, Line, Rectangle, Circle> shapes;
shapes.push_back(Point{1.0, 1.0} );
shapes.push_back(Point{1.0, 1.0} );
shapes.push_back(Circle{1.0, 1.0, .3} );
shapes.push_back(Rectangle{0.0, 0.0, 0.0, 1.0, 1.0} );


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk