0

I am fairly new to c++ and have not had much experience with headers or templates, and I have not had any experience with them combined. So, I have run into problems trying to use the class I have created. My class definitions and headers are as follows: J.h is the header file for the template class J.

#ifndef J_H
#define J_H

template<class t>
class J {
        public:
                void speak();
};

#endif

J.cpp has the function definitions for it's header.

#include "J.h"
#include <iostream>

template<class T> void J<T>::speak(){
        std::cout << "Hello from j";
}

main.cpp has the main function and tries to use J.

#include "J.h"

int main(){
        J<int> j;
        j.speak();
}

My problem is that when I compile with g++ J.h J.cpp main.cpp, I get the error undefined reference to J<int>::speak(), but doing g++ J.h J.cpp runs without any error. I am very new to templates, so any help is appreciated. Thank you in advance.

TGrossb
  • 44
  • 6
  • 1
    probably duplicate of [Why can templates only be implemented in the header file?](http://stackoverflow.com/q/495021/5980430) – apple apple May 17 '17 at 02:51

1 Answers1

0

Just put your implementation in the header file instead.

There was once standard that allow putting template implementation in its own source file (template export) but compiler supporting this feature was rare (Comeau was the only one I believe?).

IIRC, template export was even deprecated in C++1x.

Adrian Shum
  • 38,812
  • 10
  • 83
  • 131