Boost logo

Boost Users :

From: Gennadiy Rozental (gennadiy.rozental_at_[hidden])
Date: 2004-08-09 22:51:13

"Timothy Perrigo" <tperrigo_at_[hidden]> wrote in message
> I'm just now treading into the (rather intimidating) waters of template
> metaprogramming, so I'm not even sure if it will fit what I'm trying to
> accomplish. I need to create a kind of registry to keep track of
> instances of variables of different types (actually, several of these
> registries, representing different system states); variables of a type
> would be identified by an unique (integer) id. In other words, the
> variables within a particular registry represent the state of the
> system at a given point in time, so although each registry would have
> variables of the same types and ids, the values of the variables in
> different registries may be different. If the variables were all of
> the same type, a simple map would work. What I would like is a way of
> asking this registry for a variable of a specified type and id, and get
> back the appropriate instance (of the appropriate type). I.e.,
> something like the following would be ideal:
> MyType mt = registry.get<MyType>(my_id);
> Is there anything in the MPL (or elsewhere in Boost) that might help me
> accomplish what I'm looking to do? If not, does anyone have any design
> suggestions to accomplish this in another way? Any help would be
> appreciated!
> Thanks,
> Tim

I do not see too much difficulties implementing something like that:

class static_any_base {
    virtual ~static_any_base() {}

template<typename T>
struct static_any_t {
    static_any_t( T const& v ) : m_value( v ) {}

    T m_value;

class MyRegistry {
    typedef IdType int;

    template<typename T>
    add( T const& t )
        m_storage.push_back( boost::shared_ptr<static_any_base>( new
static_any_t<T>( t ) ) );
        return m_storage.size() - 1;
    template<typename T>
    T const&
    get( IdType id )
        return static_cast<static_any_t<T> const&>(
*m_storage[id] ).m_value;

    std::vector<boost::shared_ptr<static_any_base>::type> m_storage;

It may not be the safest solution (you could use dynamic_cast instead of
static one and you will get all the protection you need for the pretty small
price), but it should do the trick.



P.S. If performance is not an issue, you could use vector of boost::any or
something similar.

Boost-users list run by williamkempf at, kalb at, bjorn.karlsson at, gregod at, wekempf at