Container of templateStruct<T> with varying T
I have a simple struct which contains GUI controls in an application I'm working on. The struct is defined like
template<clas开发者_运维问答s T>
struct guiControl
{
T minValue
T defaultValue
...
}
Each control is identified by a unique integer ID in my app. I would like to access the structs with a map<int, guiControl>
, but this is not allowed:
unspecialized class template can't be used as a template argument for template parameter... use of class template requires template argument list.
OK, that makes sense to me - the compiler needs to know exactly how much space the value type of the map needs. But is there any other way for me to approximate this behavior - preferably without getting into Boost or a more complicated class heirarchy?
It would not make sense to access your controls in one map because they are of different type what means you cannot perform the same methods on them etc...
What you can do is define a general class that contains the elements every control should have and then derive special controls from that class:
template<class T>
class guiControl
{
T minValue;
T defaultValue;
/* ... */
}
Example for controls:
class Button : public guiControl<int>
{
/* ... */
int get_id() { return id; }
}
Then you can still make a map of id's and pointers to your objects, when you cast the objects pointers to the type of the base class:
map<int, guiControl<int>* > controls;
Button button;
controls[button.get_id()] = dynamic_cast<guiContorl<int>*>(&button);
Now you can access the guiControl
members (like minValue
) of your controls by id and even cast them back to their derived type but then you would have to know which type they are.
精彩评论