Boost logo

Boost :

Subject: Re: [boost] Interest in a container which can hold multiple data types?
From: Boris Rasin (boris_at_[hidden])
Date: 2015-05-04 12:51:20


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>()?


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