Undefined reference on template class

L

LaBird

Dear all,

I would like to ask what is the way to separate class
template definition from declaration in different source
files? Currently I have the following files (simplified):

// d.h -- class declaration
template<typename T>
class C {
int x;
T* p;
public:
C();
T* getp();
};


// d.cpp -- class definition
#include "d.h"

template <typename T>
C<T>::C() {
x = 0;
p = new T;
}

template <typename T>
T* C<T>::getp() {
return p;
}


// my.cpp -- using class C
#include "d.h"

main() {
C<int> c;
int *q;

q = c.getp();
return 0;
}

But when I compile the two .cpp files, I get an error
from the loader, about undefined reference on the
c.getp() and constructor. I found that this error
will not occur if I do not have the template. Why does
such error occurs for templates, and how to solve it
(apart from putting the member function definitions
into d.h)?

Thanks a lot.
 
J

Jacques Labuschagne

LaBird said:
Dear all,

I would like to ask what is the way to separate class
template definition from declaration in different source
files?

No. (Your compiler doesn't support the "export" keyword.)

The nearest hack-around is

// foo.hpp
template<typename T> class X{
void func(const T&);
}
#include "foo.cpp"

// foo.cpp
template<typename T> void X<T>::func(const T&){}
 
L

LaBird

Dear Jacques,

Thanks!

--
LaBird (Benny).

Jacques Labuschagne said:
No. (Your compiler doesn't support the "export" keyword.)

The nearest hack-around is

// foo.hpp
template<typename T> class X{
void func(const T&);
}
#include "foo.cpp"

// foo.cpp
template<typename T> void X<T>::func(const T&){}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top