I have a class that holds several vectors of objects:
struct ComponentA
{
public:
methodA1();
float data1;
...
};
struct ComponentB
{
...
};
struct ComponentC
{
...
};
struct ComponentD
{
...
};
class Assembly
{
vector<ComponentA> As;
vector<ComponentB> Bs;
vector<ComponentC> Cs;
vector<ComponentD> Ds;
};
I would like to use traits and define a function that can return reference to members like this:
template< int T >
struct ComponentTraits;
template<>
ComponentTraits<TYPEA>
{
typedef vector<ComponentA> data_type;
}
....
template< int T >
ComponentTraits<T>::data_type getComp(const Assembly & myassy)
{
...
}
such that a call
getComp<TYPEA>(thisassy)
would return a reference to As so I can manipulate at the vector level and access each component object method and data:
getComp<TYPEA>(thisassy).push_back(newcomponentA);
getComp<TYPEA>(thisassy).back().methodA1();
getComp<TYPEA>(thisassy).front().data1 = 5.0;
Thanks,
Wada
Traits aren’t going to do what you want here. C++ lacks the introspection support needed to say, “Get me the first member of class X that is of type Y.” Also, traits are intended for “tell me more about type X” kinds of operations.
Template specialization can be used for this, but they’ll be a lot of work:
Or shorter:
You may also want to read up on Typelists (Chapter 3) in Alexandrescu’s book Modern C++ Design. You might be able to use them in a Factory-like pattern, but that’s way more than an SO answer really fits.