data member 'vec' cannot be a member templ

2019-04-23 18:55发布

问题:

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.

回答1:

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.


回答2:

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.



回答3:

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;
};


回答4:

This answer applies to C++11 and earlier


There is no such thing as templated data members. The only sorts of templates are class template and function template. Your other example is a function template.

Try and think about how someone would instantiate your class. Suppose it was legal to do:

struct S
{
    template<typename T> 
    T x;
};

int main()
{
    S s;
    s.x = ????
}

The type of S must be known in order to do S s;, it can't magically change to accommodate whatever type you decide to give to x. In fact you couldn't even evaluate s.x .

To solve your problem you have to make the template parameter be a template parameter of the class containing the data member, e.g.:

template<typename T>
struct S
{
    vector<T> vec;
};

int main()
{
    S<int> s;
    s.vec = vector<int>(5);
}