Boost logo

Boost :

Subject: Re: [boost] Interest in a container which can hold multiple data types?
From: James Armstrong (armstrhu_at_[hidden])
Date: 2015-05-10 16:30:05


On Sun, May 10, 2015 at 12:11 PM, Rob Stewart <rob.stewart_at_[hidden]>
wrote:

> Create customization points. Implement the default access method and
> permit customization for other types. You could provide some common
> specializations in separate headers so users don't always have to reinvent
> the same wheel.
>

So I worked on this a little bit. What I did was make a function pointer
to allow the user to define their own access function. They could write
something along the lines of

template<typename T>
void* get_boost_any(boost::any* data)
{
   return (void*)boost::any_cast<T>(data);
}

template<typename U, typename T1, typename T2, ... typename TN>
void* get_boost_variant(boost::variant<T1,T2,...,TN>* data)
{
   return (void*)boost::get<U>(data);
}

The problem with this is there is a separate function for each T created so
a single function pointer doesn't quite work. To get around that, I am
thinking of having an array of function pointers, and the user will have to
set the function pointer for each type explicitly.

typedef data_type boost::any;
// typedef data_type boost::variant<int, double, std::string>

typedef container_type std::vector<data_type>;
// typedef container_type std::list<data_type>

container_type my_container;
// fill my_container with data

poly_adaptor<container_type, data_type> p(my_container);

p.set_get_function(get_boost_any<int>);
p.set_get_function(get_boost_any<double>);
p.set_get_function(get_boost_any<std::string>);
// p.set_get_function(get_boost_variant<int, int, double, std::string>);
// p.set_get_function(get_boost_variant<double, int, double, std::string>);
// p.set_get_function(get_boost_variant<std::string, int, double,
std::string>);

// now we can access data in p for int, double, and std::string

//iterate over all ints
for( auto itr = p.begin<int>(); itr != p.end<int>; ++p)
{
  std::cout << *itr << std::endl
}

Interested in hearing ideas on a better implementation besides this. This
is my first time really coding anything along these lines, so its really
fun/interesting thinking through these issues. But, I am sure that lack of
experience means I am overlooking some more elegant methods ;)


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