I understood the concept of templates and why do we need to define the template member functions in header file. And another option is where define template functions in cpp file and explicitly instantiate template classes as below.
template.h
#include <iostream>
using namespace std;
template <typename T> class myclass
{
public:
void doSomeThing();
};
template.cpp
#include <iostream>
#include "template.h"
using namespace std;
template <typename T> void myclass<T>::doSomeThing()
{
cout << "in DoSomething" << endl;
}
template class myclass <int>; // Why we shouldn't use template<> class myclass <int> here?
main.cpp
#include <iostream>
#include "template.h"
using namespace std;
int main()
{
myclass<int> obj;
obj.doSomeThing();
}
I am compiling on Ubuntu OS using g++ main.cpp template.cpp
and I am able to call doSomeThing()
I have couple of questions as below.
- If we need to explicitly instantiate class template, it should be
template <> class myclass <int>
But when I use this in template.cpp instead oftemplate class myclass <int>
, it is throwing undefined reference to 'myclass::doSomeThing()' error. Why we shouldn't use<>
in this case? I tried to instantiate an object for myclass (for int) as
myclass <int> obj;
instead oftemplate <> class myclass <int>;
in template.cpp as below.#include <iostream> #include "template.h" using namespace std; template <typename T> void myclass<T>::doSomeThing() { cout << "in DoSomething" << endl; } myclass <int> obj;
I thought template.cpp has both template declaration through template.h and all the template function definitions in template.cpp so creating an object for int type will create the class for int and it will contain the function definition for int type. So when g++ compiles main.cpp, it has all the functions for int type and creation of object for myclass (for int data type) will work if I compile template.cpp first and main.cpp after as
g++ template.cpp main.cpp
. But this is also throwing main.cpp:(.text+0x1f): undefined reference to `myclass::doSomeThing()' error. I am unable to understand why this is throwing error. Can anyone please help me to understand why this is not working.