简体   繁体   English

C++ std::vector 带有指向模板的指针 class

[英]C++ std::vector with pointers to a template class

In a project I am working on I am tying to make a vector with pointers to a template class.在我正在进行的项目中,我试图制作一个带有指向模板 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?有没有办法解决?

When you create a class instance you have to choose the type.创建 class 实例时,您必须选择类型。 In the definition you can write T but at the moment of create instance you have to specify the type.在定义中你可以写 T 但在创建实例时你必须指定类型。

So if you want define and not creating an instance use typedef .因此,如果您想要定义而不是创建实例,请使用typedef

You can't have a templated member.您不能拥有模板化成员。
The template must come from the class or function templated declaration.模板必须来自 class 或 function 模板化声明。

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>编译器需要在代码中的某处定义模板化类型名,例如: 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.模板化类型名是在您首次使用 function 或 class(显式或隐式)时确定的,因此您必须在调用代码可以访问的某个地方拥有模板定义和实现。

It looks like you are trying to define a new type vec<T> as a shortcut to the longer templetized expression.看起来您正在尝试将新类型vec<T>定义为更长的模板化表达式的快捷方式。 Normally, this would be done with a typedef , however C++ does not support templetized typedefs.通常,这将使用typedef来完成,但是 C++ 不支持模板化的 typedef。

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.请注意,在当前代码中,您实质上是在尝试定义一个名为vec的变量,但您没有为它指定 T 的特定类型,这就是编译器抱怨的原因。

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)目前 C++ 不支持模板类型定义,所以你必须使用最常见的解决方案,由 Herb Sutter (http://gotw.ca/gotw/079.htm) 提出

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM