0

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.

birgersp
  • 3,909
  • 8
  • 39
  • 79
  • 1
    The explicit instantiations of a template need to be in the same translation unit as the definitions of all the member functions. You can either do this by #including A.cpp in A.h, or you can do it by putting the explicit instantiations in A.cpp. You can't do it in main.cpp. – Martin Bonner supports Monica Mar 09 '17 at 12:01
  • 1
    If you want "generic and use for any type", you have to put the definition of the functions in the header. C++ tried `export` to do what you want, but it turned out not to have any benefits over just including the functions in the header. – Martin Bonner supports Monica Mar 09 '17 at 12:02
  • Thanks @MartinBonner! So to conclude; No, I can't explicitly instantiate outside of the class? Or can I? – birgersp Mar 09 '17 at 13:45

0 Answers0