I have defined a test class "Pair" with a template but I am getting compilation error. Without template, it compiles fine. So, something is coming due to template. I wonder what is wrong. The error is:
1 2 3 4 5 6 7
CMakeFiles/main.exe.dir/main.cxx.o: In function `main':
main.cxx:7: undefined reference to `Pair<float>::set_element(int, float)'
main.cxx:8: undefined reference to `Pair<float>::set_element(int, float)'
collect2: error: ld returned 1 exit status
make[2]: *** [main.exe] Error 1
make[1]: *** [CMakeFiles/main.exe.dir/all] Error 2
make: *** [all] Error 2
Pair.h file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#ifndef __Pair__
#define __Pair__
#include<iostream>
usingnamespace std;
template <class T>
class Pair
{
public:
Pair() {};
Pair(T first, T second);
void set_element(int pos, T value);
private:
T first, second;
};
#endif
Yes, that's correct. At the point where the compiler creates the class for a particular type, it needs to have the entire definition of the class available. This means that the entire definition of the class needs to be included in the translation unit.