I've read this page Why can templates only be implemented in the header file? but it's about a template class. And the constructor takes same type as class (if class is < int >, constructor also takes int, and so on). But I have simple (non-template) class. Sorry for duplication, please explain what should I do in this case?
I have a class 'Object' with field 'double d' and I want to make a template constructor. If I realize it inside the class, all works good, but if move the realisation outside of the class (from .h to .cpp), it doesn't work. Here's my code:
Object.h
class Object {
double d;
public:
template <class T> Object(T t);
};
Object.cpp
#include "Object.h"
template <class T> Object::Object(T t) {
d = t;
}
main.cpp
#include "Object.h"
int main() {
int a = 5;
Object x(a);
float b = 2.5;
Object y(b);
return 0;
}
Error appears in main.cpp in lines that creates x and y, there are:
undefined reference to `Object::Object<int>(int)'
undefined reference to `Object::Object<float>(float)'