This question already has an answer here:
I found that I cannot compile my program when I put my class member implementation outside the header. I simplified the code to show the problem more exactly.
I define my class in dog.h,
class Dog {
public:
template<typename T>
void bark();
}
I cannot template the class because I know the type of template argument only when I call bark(). The implementation is as follows,
#include "dog.h"
template<typename T>
void Dog::bark() {}
And here comes my main.cpp
#include "dog.h"
int main() {
Dog d;
d.bark<int>();
return 0;
}
I got the following compilation error,
/tmp/ccoxjr6t.o: In function `main':
test.cpp:(.text+0x10): undefined reference to `void Dog::bark<int>()'
collect2: error: ld returned 1 exit status
However everything is fine when I put the implementation to dog.h. Can anyone tell me the reason? The compiler I use is GCC-4.8.1. Thanks!
Aucun commentaire:
Enregistrer un commentaire