Reputation: 1470
In a project I am working on I am tying to make a vector with pointers to a template class.
template <typename T>
std::vector<templateClass<T>*> vec;
However, this gives me two errors:
Error C2133: vec : unknown size
Error C2998: std::vector<templateClass<T>*> vec : cannot be a template definition
If I change the code to:
std::vector<templateClass<int>*> vec;
It works fine, so I guess the problem isn't that you cant use template classes with vectors, but that you need to tell the compiler what type to use. Is there any way around this?
Upvotes: 1
Views: 6590
Reputation: 21
Currently C++ doesn’t support template typedefs so you have to use the most common solution, proposed by Herb Sutter (http://gotw.ca/gotw/079.htm)
Upvotes: 1
Reputation: 2318
It looks like you are trying to define a new type vec<T>
as a shortcut to the longer templetized expression. Normally, this would be done with a typedef
, however C++ does not support templetized typedefs.
Note, that in the current code you are essentially trying to define a variable called vec
, but you are not giving it a specific type for T and that's why the compiler is complaining.
Upvotes: 1
Reputation: 7807
When you create a class instance you have to choose the type. In the definition you can write T but at the moment of create instance you have to specify the type.
So if you want define and not creating an instance use typedef
.
Upvotes: 2
Reputation: 49221
You can't have a templated member.
The template must come from the class or function templated declaration.
template <typename T>
class blah {
std::vector<templateClass<T>*> vec;
}
The compiler needs the templated typename to be defined somewhere in the code, for example: blah<int>
If you'd have a templated member, you couldn't define the type anywhere in the code, and the compiler wouldn't be able to decide the member's type.
The templated typename is decided when you first use the function or class (either explicitly or implicitly) so you'd have to have the template definition and implementation somewhere that is accessible by the calling code.
Upvotes: 1