Niranjan Kamath
Niranjan Kamath

Reputation: 3

Creating a vector in a template class in C++

I am trying to create a vector inside a template class where the type of the vector depends on the template of the class I am defining it in. My code is as follows :

template<class T>
class A {
    vector<T*> vec;
    vec.resize(100);
}

When I try to compile it I get the following error message :

error: ‘vec’ does not name a type; did you mean ‘getc’?
     vec.resize(100);
     ^~~

Can someone please tell me how to go about defining a vector like this?

Thanks in advance.

Upvotes: 0

Views: 79

Answers (1)

john
john

Reputation: 88037

This has nothing to do with templates. This non-template code would also be an error

class A {
    vector<int*> vec;
    vec.resize(100);
}

because vec.resize(100) is not in a function. I guess you want that code to be called in the constructor, like this

class A {
    vector<int*> vec;
    A() {
        vec.resize(100);
    }
}

That is legal. Now we can turn that legal code into a template

template <class T>
class A {
    vector<T*> vec;
    A() {
        vec.resize(100);
    }
}

Upvotes: 1

Related Questions