-2

I try to implement a skiplist and run into this error

undefined reference to `SkipNode::SkipNode(std::string*, int)

Did I use templates incorrectly? Or do is this perhaps a linking problem?

Here is the really simple code (a scaled-down version):

Main.cpp

#include <iostream>
#include <string>
#include "SkipNode.h"
#include "RandomHeight.h"

using namespace std;

int main()
{
    RandomHeight rh(32, 0.5);
    string s = "Test";

    SkipNode<string> skipNode_obj(&s, rh.newLevel()); //ERROR

    for ( int i = 0; i < 10; i++ ) {
        cout << rh.newLevel() << endl;
    }

    cout << "Hello world!" << endl;
    return 0;
}

SkipNode.h

#ifndef SKIPNODE_H
#define SKIPNODE_H

template<typename T>
class SkipNode
{
    public:
        SkipNode(T* value, int h);
        int getHeight();
        T* getValue();
        virtual ~SkipNode();

        SkipNode** fwdNodes;
    private:
        T* value;
        int height;
};

#endif // SKIPNODE_H

SkipNode.cpp

#include "SkipNode.h"
#include <iostream>
using namespace std;

template<typename T>
SkipNode<T>::SkipNode(T* value, int h):value(value), height(h)
{
    fwdNodes = new SkipNode<T>* [h];
    for(int i=0; i<h; i++){
        fwdNodes[i] = nullptr;
    }
}

template<typename T>
int SkipNode<T>::getHeight()
{
    return height;
}

template<typename T>
T* SkipNode<T>::getValue()
{
    return value;
}

template<typename T>
SkipNode<T>::~SkipNode()
{
    cout<<endl;
}
UpAndAdam
  • 4,515
  • 3
  • 28
  • 46
user3490546
  • 292
  • 6
  • 16
  • 1
    See http://stackoverflow.com/questions/3749099/why-should-the-implementation-and-the-declaration-of-a-template-class-be-in-the?lq=1. The template must\* be defined in the header and cannot be split between .h/.cpp. – Zeta Apr 02 '14 at 17:47
  • possible duplicate of [Why can templates only be implemented in the header file?](http://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) – UpAndAdam Apr 02 '14 at 19:26

1 Answers1

0

Just put the definition of your class (the stuff currently in the CPP file) at the end of your header and remove the CPP file. Or alternatively, define all your methods inline.

For an explanation of why this is needed, read this question and its answers. The short version is that you are writing a template for a class and not a class itself, therefore, the whole body of the template must be accessible to the compiler while it is instantiating the template per each type (or combination of types/other template parameters.)

Community
  • 1
  • 1
yzt
  • 8,873
  • 1
  • 35
  • 44
  • ohhh thx...i should have known that... it works now! for each other, you can also use "export" template/class, but be careful it doesnt work everywhere – user3490546 Apr 02 '14 at 19:31