0

in header testh.h, i have the following

#include<stdlib.h>
template<typename T>
class X {
    public:
    T x;
    X(T i);
    void assign(T *i); 
    
};

the file obj.cpp, has the following

#include<testh.h>

template<typename T> 
X<T>::X(T i) {
    //...
}

(using obj.cpp as object files(.o) for linking)

in the main call in file test.cpp, has the following

#include<testh.h>

int main() {
    X<int> x(20);
    return 0;
}

but calling the constructor of X with template[T=int], get the linker error

/usr/bin/ld: /tmp/ccHiPTCC.o: in function `main':
test.cpp:(.text+0x28): undefined reference to `X<int>::X(int)'
collect2: error: ld returned 1 exit status

is there a get around for defining class members in a separate file while using templates?

  • 2
    Does [this](https://stackoverflow.com/questions/495021/why-can-templates-only-be-implemented-in-the-header-file) cover your question? – Nathan Pierson Dec 03 '21 at 17:36
  • `obj.cpp` did not instantiate `X::int(int)`. Which is why template implementations usually are in the header files and not in the cpp files. – Eljay Dec 03 '21 at 19:54

0 Answers0