0
votes

I'm writing a generic list for my data structures class and I think I'm having a problem with the custom templates. I have this code

ListNode.h

#ifndef LISTNODE_H
#define LISTNODE_H

#include <iostream>
using std::ostream;

template <class Datatype>
class ListNode
{
public:
    ListNode(Datatype data);
    ListNode<Datatype>* next() const;
    void next(ListNode* next);
    ListNode<Datatype>* previous() const;
    void previous(ListNode* previous);
    Datatype data() const;
    void data(Datatype data);
    void write(ostream& out) const;

private:
    ListNode<Datatype>* m_next;
    ListNode<Datatype>* m_previous;
    Datatype  m_data;
};

template <class Datatype>
ostream& operator << (ostream& out, const ListNode<Datatype>& node);

#endif  /* LISTNODE_H */

ListNode.cpp

#include <iostream>
using std::ostream;

#include "include/List/ListNode.h"

template <class Datatype>
ListNode<Datatype>::ListNode(Datatype data)
{
    m_data = data;
    m_previous = 0;
    m_next = 0;
}

template <class Datatype>
ListNode<Datatype>* ListNode<Datatype>::next() const
{
    return m_next;
}

template <class Datatype>
void ListNode<Datatype>::next(ListNode<Datatype>* next)
{
    m_next = next;
}

template <class Datatype>
ListNode<Datatype>* ListNode<Datatype>::previous() const
{
    return m_previous;
}

template <class Datatype>
void ListNode<Datatype>::previous(ListNode<Datatype>* previous)
{
    m_previous = previous;
}

template <class Datatype>
Datatype ListNode<Datatype>::data() const
{
    return m_data;
}

template <class Datatype>
void ListNode<Datatype>::data(Datatype data)
{
    m_data = data;
}

template <class Datatype>
void ListNode<Datatype>::write(ostream& out) const
{
    out << m_data;
}

template <class Datatype>
ostream& operator << (ostream& out, const ListNode<Datatype>& node)
{
    node.write(out);
    return out;
}

main.cpp

#include <iostream>
using std::cout;
using std::endl;

#include "include/List/ListNode.h"

int main(int argc, char** argv) 
{
    ListNode<int> node(10);

    cout << node;

    return 0;
}

So when I try to compile that I get:

main.cpp:9: undefined reference to `ListNode::ListNode(int)'

main.cpp:9:(.text+0x21): relocation truncated to fit: R_X86_64_PC32 against undefined symbol `ListNode::ListNode(int)'

I would appreciate it if someone could tell me what I'm doing wrong

1

1 Answers

0
votes

It's very simple, you must put template code in header files otherwise you get link errors. Template code is special. The compiler needs to know the definition (not just the declaration) of any template at the point it is being used. So all template code should go in header files.

See here for more details.

Delete ListNode.cpp and put all it's code in ListNode.h