When I try to compile this, I get the following error messages:
In function 'int main()':
error: invalid use of 'struct Entry::Sub<int>'
error: expected ';' before 'sub'
error: 'b' was not declared in this scope
error: expected primary-expression before 'float'
error: expected ';' before 'float'
error: 'c' was not declared in this scope
error: expected primary-expression before 'char'
error: expected ';' before 'char'
error: 'd' was not declared in this scope
error: expected primary-expression before 'double'
error: expected ';' before 'double'
It's quite obvious what I'm trying to achieve here. So, tell me, what am I doing wrong here?
Basically, I'm trying to 4 create instances of Entry::Sub with different types. When defined, I push the instances into the reg.entries vector. That's it.
I still don't know why it's disliking the instance definitions.
It looks like you want a „generic” variable type. If your generic variable will only store values of primitive types then union is all you need. Otherwise, your “Entry” structure should contain a pointer to a generic variable’s data, allocated from the heap. Or you could simply use boost::any.
BaseSub is not really needed in the above, quite limited, example. But you will need it to implement even very basic functionality. The problem is, Entry doesn't know anything about the type of data it holds. Lets suppose you want to write an assignment operator. How will you copy the data without knowing its type? It's quite obvious that the method to perform copying should be a part of Sub. And how will you call this method from Entry? Declaring a pure virtual "clone" function in BaseSub, and implementing it in Sub, is the simplest technique to accomplish this task.
If you only have specific types you want to use, you can use inheritance from a generic class and have a vector of the generic class, then push the other class objects onto the vector. I wrote some code below but I can't test it for validity or even to see if it works because I am away from any compiler. I tested this code and fixed some mistakes and it now works perfectly!
Of course, this is just a basic example...I didn't include constructors or assignment operators to make it easier...I just wanted to prove that it works like you want. Also...the pointers in the vector would of course become invalid if the ch, in, and db variables were destroyed by going out of scope...so it may be better to dynamically create them with new.