I am wondering if instead of doing something like this:
void attrSetValue(Entity* entity, int index, std::string value)
{
dynamic_cast<stringAttribute*>(entity->attribute[index])->value = value;
}
void attrSetValue(Entity* entity, int index, int value)
{
dynamic_cast<intAttribute*>(entity->attribute[index])->value = value;
}
Can a generic function be written to accept whatever type is passed and cast it correctly to save the data? Something like a template. I can see that a template itself is problematic, seeing that it isn't doing the same thing on different types, although it is almost doing the same thing on different types. It is just the dynamic_cast type that changes. To make the question easier, is there a way of simplifying the code by getting rid of the overloading? Does the overloading impact the performance in any way?
To explain a bit what's going on above, seeing that this is only a very small section of the code, the attributes of the entity's can be of any type (int, double, string, char, bool, etc..) - thus using inheritance with a virtual function to get the attribute values to have different types. Theses attributes are added to a vector on the Entity struct/class. E.g.
std::vector<attribute*> attributes;
It looks like you want to do type mapping:
template <typename T> struct TypeMap;
template<> struct TypeMap<int> { typedef intAttribute type; };
template<> struct TypeMap<string> { typedef stringAttribute type; };
template <typename ValueT>
void attrSetValue(Entity* entity, int index, ValueT value)
{
dynamic_cast<typename TypeMap<ValueT>::type*>(entity->attribute[index])->value = value;
}
Performance will be the same as your original code. You can do this in a more fancy way using Boost MPL to do the type mapping, but it amounts to the same thing.