模板类指针c ++声明 [英] Template class pointer c++ declaration
问题描述
template <typename T>
class Node
{...};
int main
{
Node* ptr;
ptr = new Node<int>;
}
无法编译我必须将指针声明为
Will fail to compile I have to to declare the pointer as
Node<int>* ptr;
为什么在声明指针时必须指定类型我还没有创建类,为什么编译器必须知道它将指向什么类型。
Why do I have to specify the type when declaring a pointer I haven't created the class yet, why does the compiler have to know what type it will be pointing to. And is it not possible to create a generic pointer and decide afterwards what type I want to assign it.
推荐答案
模板解析类型的解决方案编译时。当你为它指定新的 Node< int>
对象时,指针必须在编译时知道它是什么类型。
Templating resolves types at compile-time. When you assign the new Node<int>
object to it, the pointer must know at compile-time what type exactly it is.
节点< int>
和节点< std :: vector>
(你的对象的二进制布局完全根据模板参数更改),所以它没有任何意义,有一个未解决的指针类型的模板。
Node<int>
and Node<std::vector>
can be very different in the binaries (the binary layout of your object changes completely according the template parameter) so it doesn't make any sense to have an unresolved pointer type to a template.
首先为您的节点使用一个共同的父类:
You should define first a common parent class for your nodes:
class NodeBase
{ ... }
template<typename ValueT>
class Node : public NodeBase
{
...
};
NodeBase* ptr;
这篇关于模板类指针c ++声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!