But when I divide it, I get the following error:
//main.c
// class templates
#include <chrono>
#include <iostream>
#include <cstdlib>
#include "timer.h"
usingnamespace std;
usingnamespace std::chrono;
int main ()
{
mypair <milliseconds> myobject ((milliseconds)58080, (milliseconds)75);
cout << myobject.getmax().count();
return 0;
}
//timer.h
template <class T>
class mypair
{
T a, b;
public:
mypair() {}
mypair (T first, T second)
{
a=first;
b=second;
}
T getmax ();
};
//timer.c
#include "timer.h"
template <class T>
T mypair<T>::getmax ()
{
return a;
}
Template functions have to be declared and defined in the same file.
PS: As an aside, I was going to say how I've lost count of how many times I've said this, and then I Googled the above sentence and found I had already said it almost exactly a year ago.
Thanks for your help.
However, I still found a way by which the files can remain split.
1 2 3 4 5 6 7 8 9
//Just add this at the end of the .cpp file
templateclass mypair<nanoseconds>;
templateclass mypair<microseconds>;
templateclass mypair<milliseconds>;
templateclass mypair<seconds>;
templateclass mypair<minutes>;
templateclass mypair<hours>;
This only work with this case, but you can do it for other to.
Yes, that works too, but it's not too different from just moving the definition to the header. IMO, it's worse because you have to add one more line for every unique usage of the template. If you move the definition to the header you can simply forget about it.