I tried to make a template class for an implementation of a 3D vector. Relevant snippet of the 2 files (vec3d.h and vec3d.cpp) are here on pastebin.
The main.cpp is as follows:
#include "vec3d.h"
#include <iostream>
using namespace std;
int main()
{
Vec3D<double> a(1,2,3), b(2,4,5), c;
c = 2.3*b;
cout<<c._x;
return 0;
}
On compiling it with g++ main.cpp vec3d.cpp vec3d.h
the following error occurs:
In function `main':
main.cpp:(.text+0x124): undefined reference to `Vec3D<double> const operator*<double>(double, Vec3D<double> const&)'
collect2: error: ld returned 1 exit status
I have put the definition and declarations of the functions separately, but I have also instantiated the template for double
.
Funnily enough, c = b*2.3
does not throw an error. Any reasons?
I am also getting the same error on several other functions (like <<, ==, / all are declared in similar fashion)
What am I doing wrong?
[[EDIT]]
I instantiated the class, as should be, but I didn't instantiated the template functions which are present outside of the class. Apparently, I have to instantiate the too. Didn't know that.
More: Refer to this question. Every C++ unit defined using a template has to be instantiated if the definitions are in a separate file from the file with declarations, not just classes