I'm trying to create and use a template class, like so:
ClassA.h
#ifndef CLASSA_H
#define CLASSA_H
template <class T>
class ClassA
{
public:
ClassA(T value);
T getValue();
private:
T value;
};
#endif /* CLASSA_H */
ClassA.cpp
#include "ClassA.h"
template<class T>
ClassA<T>::ClassA(T value) : value(value)
{
}
template<class T>
T ClassA<T>::getValue()
{
return value;
}
Now, to actually use this template class for anything, I have to instantiate the class template with the type(s) I'm going to use, like so:
template class ClassA<int>;
I'd rather not have this instantiation in the class header, since the class is generic and I want to (in principle) use it for any type. So I'm trying to put it in my main.cpp
:
#include <iostream>
#include "ClassA.h"
template class ClassA<int>;
int main(int argc, char** argv)
{
ClassA<int> a(1337);
std::cout << a.getValue() << std::endl;
return 0;
}
But now, the compiler gives the following error:
main.cpp:10: undefined reference to `ClassA::ClassA(int)'
Do I have to instantiate the template class in the class header? Or can I instantiate it somewhere else? Can I instantiate it in the main.cpp
at all? If no, why not?
EDIT: The question referred to when marking this as a duplicate states that you can use explicit instantiations. Not where, which is what I'm asking here.