0

I have a simple struct which contains GUI controls in an application I'm working on. The struct is defined like

template<class 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?

japreiss
  • 11,111
  • 2
  • 40
  • 77
  • 8
    Is it feasible to derive all controls from a common base class? – Kerrek SB Aug 24 '11 at 14:46
  • 2
    If you can use a common base class without template, maybe you can use map< int , shared_ptr< common_base_class> > – winterTTr Aug 24 '11 at 14:54
  • Maybe one of the answers of http://stackoverflow.com/questions/7154602/hold-any-kind-of-c-template-class-in-member-variable helps? – PlasmaHH Aug 24 '11 at 14:56
  • 1
    A unique integer ID. Say, perhaps you mean something like a *pointer*? – Puppy Aug 24 '11 at 15:02
  • 1
    Is there really any need to make this class a template? Just use `long long` or `double` and be done with it. – Mark Ransom Aug 24 '11 at 15:16
  • @Mark Ransom I ended up using your suggestion. I didn't want to get into a class hierarchy for this simple task. Since I only need booleans, small ints, and doubles, I can just use doubles for everything. I think this is an example of a situation where the polymorphism from class inheritance is overkill, but the polymorphism of a dynamically typed programming language would be really useful. – japreiss Aug 24 '11 at 18:24

1 Answers1

0

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.

user905686
  • 4,491
  • 8
  • 39
  • 60