By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
458,107 Members | 1,617 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 458,107 IT Pros & Developers. It's quick & easy.

Undefined reference on template class

P: n/a
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.

--
LaBird (Benny).
Jul 22 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
LaBird wrote:
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&){}

Jul 22 '05 #2

P: n/a
Dear Jacques,

Thanks!

--
LaBird (Benny).

"Jacques Labuschagne" <ja*****@clawshrimp.com> wrote in message
news:xH********************@news02.tsnz.net...
LaBird wrote:
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&){}

Jul 22 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.