Pregunta

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.

¿Fue útil?

Solución

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(){
//...
}
//...

Otros consejos

Compiler must know the implementation for instantiate template class for every type T. You can put all the code into .hpp or include .cpp from .hpp. There are other techniques for separate compilation.

Try

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

And same layout for all other functions. If you still get undefined references, then put your functions into the .h so the compiler can find them.

Its a common problem with templates. Try moving your implementaion into the header file or implement the function while defing. This will solve your problem.

For more details please go through : Why templates needs to be implemented only in the header file?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top