When speaking about attribute lists I mean a generic list which stores additional information for a class.
The simplest case:
A class has a std::map<std::string, std::string>. The first string names the attribute (like "Color"), the second string describes the value (like "Yellow").
In this example another class which uses these attributes needs to check if a certain attribute-name is existing in the map and then parse the value.
However this isn’t the best concept when talking about performance.
How would you implement such an attribute list?
Are there any design patterns or libraries which just do something like that?
I’m especially interested in a C++-way of doing this, but if there are language-independant solutions, please post them too.
An attribute list could be used in cases where a class needs to have dynamic attributes and the user does not want to inherit for each attribute.
If that helps, you could check my other question relating to that topic:
Attributelists or inheritance jungle?
EDIT:
Of course I forgot some information (thanks to the comments):
The attributes could be applied to objects. There could be different attributes for objects of the same class. The attributes an object has can change (the value can change, there could be attributes added/removed)
Hope this clearifies it a bit.
I did something similar.
If the attributes are common for all instances of your class, make a separate Meta description of your class in which you describe the attributes. Then, per instance provide a simple vector of type boost::any (I don’t use boost::any but something similar that we wrote ourselves).
If the attributes can be different per instance, make a map per instance where the key is an atom and the value is boost::any (or something similar). Under Windows atoms are a kind of numerical representation of a string. First use strings to indicate the ‘attribute name’, then convert this to an atom and use this as key in the map. Using the numerical atoms instead of strings will speed up the look up of attributes in the map (provided you keep the atom value somewhere and you don’t need to perform the string-to-atom lookup everytime you want an attribute value).
Don’t use attributes as your normal way of storing class data members. If you do this, debugging will become a nightmare, since it will be very very very difficult to see what the actual values in your class are. Also putting watch points will become impossible.
Only use these attributes to store things that you can’t put in a normal data member, e.g.:
– you don’t know the attributes beforehand (e.g. they could be customer-specific)
– you don’t want to introduce a dependency (even by name) between two classes