I have the following two lines in a header in order to declare a vector containing a template:
template <class t>
std::vector <t> vec;
However I get the following error:
data member 'vec' cannot be a member template
What did I do wrong?
Edit: I don't know that I was understood correctly, I am trying to declare a vector which contains a template, I know that this can be done since one can have the following:
template <class T>
void funct(vector <T> v){
}
This function takes a vector of a template as its parameter. I wish to do the same thing except with declaring the vector in a header in order to allow the vector to contain anything.
Such a vector can't contain anything.
Let's suppose that a compiler lets you declare such a vector and you write:
//...
A Aobj;
vec.push_back(Aobj);
//...
Then the size of one element in vec
will be the sizeof(A)
. But next you write:
//...
B Bobj;
vec.push_back(Bobj);
//...
What will the size of one element here be?
Anyway, as a workaround you may declare vector<void*> vec
so the vector can contain a pointer to anything you want.
The template <>
statement is only used when declaring a function template or a class template. For example you can use it when you declare (and define) a class:
template <typename T>
class TemplateClass {
/* definition */
};
Or a function:
template <typename T>
void templateFunc(T value) {
/* definition */
}
When creating an instance of the class, you can't use the template <>
statement. Instead you specify a template parameter like this:
TemplateClass<int> tc;
And when calling a template function:
int i = 1;
templateFunc(i); // <-- Automatic template deduction to int.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With