data member 'vec' cannot be a member template

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 as one can have the following:

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


}

this function takes a vector of a template as it's 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.


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.

Such vector can't contain anything. Let's suppose that a compiler let you declare such a vector, and you write a code like

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

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

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

What the size of one element here should be?

Anyway, as a workaround you may declare vector<void*> vec this going to contain a pointers to anything you wanted.


Vector always need a class T as template. But the template should be put ahead of class declaration.

You probably mean

template<class T> 
class A {
private:
std::vector<T> vec;
};
链接地址: http://www.djcxy.com/p/73520.html

上一篇: 是否有可能限制Travis中的并发构建

下一篇: 数据成员'vec'不能成为成员模板