Alex Rivera | Logout

c++ class with template cannot find its constructor

Asked 2009-03-13T20:05:13.483
15

I have a problem I don't really understand. I have a class Node.

template<class T>
class node {
protected:
    T _data;
public:
    node(T data);   
};

This is in "node.h" file. In "node.cpp" file, there is this constructor:

#include "node.h"

template<class T>
node<T>::node (T data) {
    _data = data;
}

While the compiler finds no error, the linker (ld) tells me:

/usr/bin/ld: Undefined symbols:

node<int>::node(int)

the weird part... if I move the constructor from .cpp to .h file, everything works fine. Where is the problem?

Edit
Report

2 Answers

1

implicit instantiation is turned off, you need

template class node<int>;

somewhere in your code (node.cpp maybe)

EDIT: bad answer, it's probably not the case.

answered 2009-03-13T20:13:25.850
1
// You can put templates declaration in header and definition in source  
// node.h or wherever you include file gets included
extern template class node<int>;

// node.cpp or where ever source file you want to use it
// But use it only once for each type of generated class
template class node<int>;
answered 2012-08-20T15:01:30.287

Your Answer