nested template classes.

So I have a template class like this:

1
2
3
4
5
6
7
template <class T>
class Input {
public:
    Input(T * input):input_(input) {};
private:
    T * input_;
};


But then I have another non-templated class like this:

1
2
3
4
5
6
class Form{
public:
    Form(vector<Input*> inputs):inputs_(inputs) {};
private:
    vector<Input*> inputs_;
};


Does the Form class have to be a template as well? Is it even legal to store template classes in a vector if each of the templates types are potentiall different?
The thing you need to understand is that Input is not a class. It's a template -- sort of like an outline for a class. Therefore you cannot have a Input*. Which further means that vector<Input*> will not compile.

Input<int> is a class, Input<float> is a class, but Input is not a class.

So the short answer is yes. If you want to do it this way, Form will also need to be a template:

1
2
3
4
5
6
7
template <class T>
class Form{
public:
    Form(vector<Input<T>*> inputs):inputs_(inputs) {};
private:
    vector<Input<T>*> inputs_;
};



Another solution would be to make Input polymorphic. This may or may not work depending on what Input is doing:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Input
{
public:
  virtual ~Input() { }
};

template <class T>
class InputType : public Input  // InputType<int> would derive from Input
{
  //...
};

class Form
{
  std::vector<Input*> inputs;  // now Input IS a class, so this will work
};
That's perfect actually. Would I have to use a different letter for the form template? I mean if I have

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
template <class T>
class Input {
public:
    Input(T * x): x_(x);
private:
    T * x_;

};

template <class T>
class Form{
public:
    Form(Input<T> * y): input_(y) ;
private:
    Input<T> * input_;
};


does Form need to be like a U or something or can it be T as well:

Form can use T as well.
Thank you!!
Topic archived. No new replies allowed.