Search code examples
c++templatesred-black-tree

Template Compiles in Header but not in Implementation


I am implementing a Red-Black tree in C++, and want to use a templated class for any type of input. This is what I have in the header:

template <class T>
class RBtree{
public:
    RBtree();
    ~RBtree();
    //...
private:
    //...
};

And in the .cpp file:

RBtree::RBtree(){
    //...
}
//...

When I try to compile in Xcode, I get an error of "Expected a class or namespace", but wasn't the constructor already defined in the header? I also get errors for all method implementations in my .cpp file.

Edit: Yochai's answer below is correct.


Solution

  • First of all, the function implementation of a template class must be "visible" to any code that uses it.
    So you should implement the template class in the header file.

    Second, the right syntax is:

    template <class T>
    RBtree<T>::RBtree(){
    //...
    }
    //...