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.
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.