An STL container with different types of content?

Let's say I have different types of components that are structures. Perhaps I have TransformComponentandRigidBodyComponent

Now this is the problem: I want something like std::mapwhere you map the component type and identifier to the component. Ides are what binds components together. Which container should I use for this? I can’t use std::map<std::typeindex, std::map<id_t, T>>, because the type Tdepends on what type of indexex you use to index the first map.

+4
source share
4 answers

. , "" . , " " , ++ - .

BTW, :

, . ? ?

, , , , . , , .

+1

, , BOOST:
: . (http://www.boost.org/doc/libs/1_54_0/doc/html/any.html)
: , , (http://www.boost.org/doc/libs/1_54_0/doc/html/variant.html)

, .

, :

typedef boost::variant<TransformComponent, RigidBodyComponent> my_struct;
std::map<std::typeindex, std::map<id_t, my_struct> > cont;
...
std::typeindex index = std::type_index(typeid(TransformComponent));
std::map<id_t, my_struct> & m = cont[index];
id_t id = ...;
TransformComponent & component = boost::get<TransformComponent>(m[id]);

, . , boost:: any boost:: .

P.S. , boost:: mpl.

0

, , , .

:

#include <iostream>

using namespace std;

struct ent
{
    int myInt;
};

struct floats
{
    float float1;
    float float2;
};

struct container
{
    bool isTypeFloats;

    union
    {
        ent myEnt;
        floats myFloats;
    };
};

void main( void )
{
    ent a = { 13 };
    floats b = { 1.0f, 2.0f };
    container c;
    container d;

    cout << b.float1 << " " << b.float2 << endl;

    c.isTypeFloats = false;
    c.myEnt = a;

    d.isTypeFloats = true;
    d.myFloats = b;

    //correct accessor
    if( c.isTypeFloats )
    {
        cout << c.myFloats.float1 << " " << c.myFloats.float2 << endl;
    }
    else
    {
        cout << c.myEnt.myInt << endl;
    }

    if( d.isTypeFloats )
    {
        cout << d.myFloats.float1 << " " << d.myFloats.float2 << endl;
    }
    else
    {
        cout << d.myEnt.myInt << endl;
    }
}

, : std::vector< container >

, :

  • . , int 4 , float 4 , ent, floats, 4 , ' m ent. , , .
  • , , , , ++ . void*. , : std::vector< void* > myVec, : myVec.push_back( &x ) x - , ent . , , , , - : cout << ( ( ent* )myVec[0] )->myInt << endl;
  • , , , , , , , , :

    struct container2 {   bool isTypeFloats;   void * myUnion; }

0
0
source

All Articles