Mar 4, 2011 at 8:28am UTC
Hi everybody.
I have a template class which works fine:
1 2 3 4 5 6 7 8 9
template <class T>
class Flag {
string flagName;
vector<T> paramList;
typename vector<T>::iterator it;
public :
Flag <T>(string, string, bool );
};
The problem is that I have another class which should store a vector of object of the first class, but I have no idea on how to implement it. It should be something like:
1 2 3 4 5 6 7 8 9 10 11
class CmdLine {
Module *module;
vector<Flag<T> > cmdLineVect; // WRONG!!!
public :
CmdLine (Module*);
~CmdLine (void );
void addFlag(Flag<T> );
};
But of course it does not work...
Could you give me some advices? What are the possible ways to achieve my goal?
Thanks in advance!
Last edited on Mar 4, 2011 at 8:29am UTC
Mar 4, 2011 at 9:22am UTC
class CmdLine is not a template class, so the T on these two line here:
vector<Flag<T> > cmdLineVect;
void addFlag(Flag<T> );
have no relevance.
Turn them concrete types - For example
1 2
vector<Flag<int > > cmdLineVect;
void addFlag(Flag<int > );
or turn CmdLine into a template class as well.
1 2 3 4 5 6 7 8 9 10 11 12
template <typename T>
class CmdLine {
Module *module;
vector<Flag<T> > cmdLineVect;
public :
CmdLine (Module*);
~CmdLine (void );
void addFlag(Flag<T> );
};
Last edited on Mar 4, 2011 at 9:26am UTC
Mar 4, 2011 at 9:37am UTC
Turning them into a concrete type makes no sense to me, because I loose the power of template implementation.
Your second suggestion is not duable too, because if I do this
CmdLine <int > *commandLine = new CmdLine<int > (prog);
I create an object CmdLine with a vector of object Flag<int>. But this is not what I want.
I would like to define a vector that could store for example one Flag<int>, one Flag<float> and one Flag<string>.
Is that possible? I'm wondering if it's possible to do something like that with inheritance...
Or maybe my approach is simply wrong...
Mar 4, 2011 at 12:51pm UTC
Last edited on Mar 4, 2011 at 12:52pm UTC
Mar 4, 2011 at 2:14pm UTC
Thank you.
But is there a solution that not involves boost libraries?
Mar 4, 2011 at 2:25pm UTC
caneta wrote:I'm wondering if it's possible to do something like that with inheritance...
It is. The idea is to have an abstract Flag class and derive a templated class from it.
1 2 3 4
class BaseFlag {/*...*/ };
template <class T>
class Flag : public BaseFlag {/*...*/ };
Then, you can do something like this:
1 2 3 4 5 6
vector<BaseFlag*> cmdLineVect;
cmdLineVect.push_back(new Flag<int >(-12));
cmdLineVect.push_back(new Flag<double >(5.5));
cmdLineVect.push_back(new Flag<char >('d' ));
//etc...
caneta wrote:But is there a solution that not involves boost libraries?
Yes. Check this out ->
http://www.cplusplus.com/forum/general/33247/
EDIT: Fixed a horrible syntax error...
Last edited on Mar 4, 2011 at 6:26pm UTC