Reputation: 33
I would like to make a class to store auxillary data in arbitrary objects - what is a clean way of doing this?
class A{
std::string _name;
int _val;
void * _extraData;
//I want to implement these methods
void setExtraData(void * data){
//
}
void * getExtraData(){
}
};
class B{
std::vector<A *> v;
void foo(){
//use A here - _extraData will
//be a (say) a vector<int>
}
};
Upvotes: 2
Views: 1803
Reputation: 96241
I would start with boost::variant
if you have a known set of types or boost::any
if not. You can always evaluate your design and see if polymorphism with an abstract interface can solve your problem too (sometimes it doesn't help). More details about the real problem you're trying to solve could help elicit better answers.
Upvotes: 7
Reputation: 8958
templates, if you know at compile time which data type is going to be used:
template typename T
class A{
std::string _name;
int _val;
T _extraData;
void setExtraData(T data){
}
T getExtraData(){
}
};
class B{
std::vector<A<int> *> v;
void foo(){
}
};
If you don't know at compile time, i.e. it depends for example on user input, than a union
or boost::any
(as proposed by @chris) is the solution.
Upvotes: 0