Search code examples
c++shared-ptr

Why can't I use same templates for different class?


I have this code where I am trying to use the same template in two different class. When I compile, I get error:

#include <iostream>
#include <memory>

template <class T>
class Node

{
    public:
    int value;
    std::shared_ptr<Node> leftPtr;
    std::shared_ptr<Node> rightPtr;
    Node(int val) : value(val) {
         std::cout<<"Contructor"<<std::endl;
    }
    ~Node() {
         std::cout<<"Destructor"<<std::endl;
    }
};

template <class T>
class BST {

    private:
        std::shared_ptr<Node<T>> root;

    public:
        void set_value(T val){

            root->value = val;
        }
        void print_value(){
            std::cout << "Value: " << root.value << "\n";
        }
};

int main(){

    class BST t;
    t.set_value(10);
    t.print_value();

    return 1;
}

Errors:

g++ -o p binary_tree_shared_pointers.cpp --std=c++14
binary_tree_shared_pointers.cpp:39:8: error: elaborated type refers to a template
        class BST t;
              ^
binary_tree_shared_pointers.cpp:21:7: note: declared here
class BST {
      ^

Solution

  • You have not specified the type of BST. A template is an incomplete type unless you specify it accordingly. Another option is that the compiler can deduce the type somehow. Otherwise it is an incomplete type - thus you got an error.

    If you want to make a tree of type int for example it should be:

    BST<int> t;
    t.set_value(10);
    t.print_value();
    

    Note that you don't need the class keyword to declare t.