The 'vec' data item cannot be a member template

I have the following two lines in the header to declare a vector containing a pattern:

template <class t> std::vector <t> vec; 

However, I get the following error: the 'vec' data item cannot be a member template. What did I do wrong? Edit: I don’t know that they understood me correctly, I’m trying to declare a vector containing a template, I know that this can be done, because you can have the following:

 template <class T> void funct(vector <T> v){ } 

this function takes the template vector as a parameter, I want to do the same thing except declare the vector in the header so that the vector can contain anything.

+7
c ++ vector templates
source share
4 answers

The template <> operator is used only when declaring a function template or class template. For example, you can use it when you declare (and define) a class:

 template <typename T> class TemplateClass { /* definition */ }; 

Or function:

 template <typename T> void templateFunc(T value) { /* definition */ } 

When creating an instance of a class, you cannot use the template <> operator. Instead, you specify a template parameter as follows:

 TemplateClass<int> tc; 

And when calling the template function:

 int i = 1; templateFunc(i); // <-- Automatic template deduction to int. 
+2
source share

Such a vector cannot contain anything. Suppose the compiler allows you to declare such a vector, and you write code like

 //... A Aobj; vec.push_back(Aobj); //... 

Then the size of one element in vec will be sizeof(A) . But next time you write

 //... B Bobj; vec.push_back(Bobj); //... 

What should be the size of one element?

Anyway, as a workaround, you can declare vector<void*> vec , this will contain pointers to everything you wanted.

+2
source share

There are no elements such as template data elements. The only types of templates are a template template and a template template. Another example is a function template.

Try to think about how someone will create your class. Suppose this was legal:

 struct S { template<typename T> T x; }; int main() { S s; sx = ???? } 

Type S must be known to make S s; , it cannot magically change to accommodate any type that you decide to pass x . In fact, you could not even evaluate sx .

To solve your problem, you must make the template parameter a parameter of the class template containing the data item, for example:

 template<typename T> struct S { vector<T> vec; }; int main() { S<int> s; s.vec = vector<int>(5); } 
+1
source share

A vector always needs a class T as a template. But the template must be placed before the class declaration.

You probably mean

 template<class T> class A { private: std::vector<T> vec; }; 
0
source share

All Articles