3

Moved from this question Storing C++ template function definitions in a .CPP file, I tried to separate the code of a templated class in a header and a source file. However, I failed, but I hope one can shed some light in the situation. Note that the difference with the question is that he has a templated function, not a class.

file.h

template<typename T>
class A {
public:
    A();
private:
    T a;
};

file.cpp

#include "file.h"

template<typename T>
A::A() { a = 0; }

template<int> class A;

and main.cpp

#include "file.h"

int main() {
    A<int> obj;
    return 0;
}

and the errors:

../file.cpp:4:1: error: invalid use of template-name ‘A’ without an argument list  A::A() { a = 0; }  
^ In file included from ../file.cpp:1:0: ../file.h:1:10: error: template parameter ‘class T’  template<typename T>
^ ../file.cpp:6:21: error: redeclared here as ‘int <anonymous>’  template<int> class A;
^ make: *** [file.o] Error 1
Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305

1 Answers1

4

Modify your .cpp file like this:

template<typename T>
A<T>::A() { a = 0; } // note the <T>

template class A<int>;
gsamaras
  • 71,951
  • 46
  • 188
  • 305
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218