C++ undefined reference to template class method [duplicate]

倖福魔咒の 提交于 2019-11-28 00:35:11

Typically you want your template methods in the header, so they are compiled when needed. In case you really want to hide it in the implementation file, you have to explicitly instantiate the template in Graph.cpp like

template class  Graph<string>;

Since you have to do that for every type T you intend to use with Graph<T>, the point of the template class is somewhat defeated and you better put everything into the header

You need to define member functions in a header file, because when instantiating a template, the compiler needs to have access to the implementation of the methods, to instantiate them with the template argument.

In your example:

template <class T> 
class Graph  {    
public:
    void InsertVertex(T val) {
        Node<T> *temp = new Node<T>(val);

        if(head == NULL) 
            head = temp;

        // ... 
    }

    // ...

private:
    Node<T> *head;
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!