Template class pointer c++ declaration

前端 未结 5 1792
误落风尘
误落风尘 2021-01-30 23:42
template 
class Node
{...};

int main
{
    Node* ptr;
    ptr = new Node;
}

Will fail to compile I have to to declare the

5条回答
  •  迷失自我
    2021-01-31 00:13

    Templating resolves types at compile-time. When you assign the new Node object to it, the pointer must know at compile-time what type exactly it is.

    Node and Node 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
      class Node : public NodeBase
    {
     ...
    };
    
    NodeBase* ptr;
    

提交回复
热议问题