File main2.cpp:
#include "poly2.h"
int main(){
Poly<int> cze;
return 0;
}
File poly2.h:
template <class T>
class Poly {
public:
Poly();
};
File poly2.cpp:
#include "poly2.h"
template<class T>
Poly<T>::Poly() {
}
Error during compilation:
src$ g++ poly2.cpp main2.cpp -o poly
/tmp/ccXvKH3H.o: In function `main':
main2.cpp:(.text+0x11): undefined reference to `Poly<int>::Poly()'
collect2: ld returned 1 exit status
I’m trying to compile above code, but there are errors during compilation. What should be fixed to compile constructor with template parameter?
The full template code must appear in one file. You cannot separate interface and implementation between multiple files like you would with a normal class. To get around this, many people write the class definition in a header and the implementation in another file, and include the implementation at the bottom of the header file. For example:
Blah.h:
Blah.template:
And the preprocessor will do the equivalent of a copy-paste of the contents of
Blah.templateinto theBlah.hheader, and everything will be in one file by the time the compiler sees it, and everyone’s happy.