Template class pointer c++ declaration

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

    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.

    There are lots of things you're allowed to do with a pointer, just to list a very few:

    • call one of many functions based on the pointer's type
    • index from it (on the assumption that it points to the first elements in a contiguous array of such objects)
    • take the size of the pointed-to object
    • pass it to a template where the pointer-type is a parameter

    For the compiler to generate code to do these efficiently, it needs to know the type of the pointer. If it defered the decisions until it saw the type of the pointer, then it would need to either:

    • compile efficient code for every possible type the pointer might later take (making a hugely bloated program), or
    • create inefficient code that can handle all the possible types through some worst-case pessimistic clumsy behaviours, or
    • embed a copy of itself (the compiler) into your C++ program so it can complete it's job when it's got the necessary information - that would make every trivial program huge (and slow)

    And is it not possible to create a generic pointer and decide afterwards what type I want to assign it.

    Kind of... you have many options:

    • use a void*, but before it can meaningfully operate on the pointed-to-type again you'll need to manually cast it back to that type: in your case that means recording somewhere what it was then having separate code for every possibility
    • use boost::any<> - pretty much like a void*, but with safety built in
    • use boost::variant<> - much safer and more convenient, but you have to list the possible pointed-to types when you create the pointer
    • use a runtime polymorphic family of objects and virtual dispatch... this is classic Object Oriented Programming... you have a pointer to an "abstract" Node that declares the shared functions and member data you'd use to operate on any particular type of node, then the templated Node class derives from that abstract Node and implements type-specific versions of the functions. These are then called via a pointer to the base class using virtual functions.

提交回复
热议问题