Template class pointer c++ declaration

前端 未结 5 1790
误落风尘
误落风尘 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:07

    The simple answer is because C++ uses (fairly) strict static type checking. Node is a completely unrelated type to Node, and when the compiler sees ptr->doSomething(), it has to know whether to call Node::doSomething() or Node::doSomething().

    If you do need some sort of dynamic generality, where the actual type ptr will point to will only be known at runtime, you need to define a base class, and derive from that. (It's a fairly common idiom for a class template to derive from a non-template base, precisely so that the generality in the pointers can be resolved at runtime.)

提交回复
热议问题