0

My aim to create a very simple class template. I can do it in one .cpp file, but I insist on having the same class defined in .h file, its method in .cpp file and finally execute it in .cpp (main) and have some troubles.

So, in class.h I have what follows:

#include<iostream>

using namespace std;


template <class T>
class templateClass {
    T x, y;
public:
    templateClass(T, T); // constructor
    T bigger();
};

On the hand in methods.cpp there is:

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

using namespace std;


template <class T>
templateClass <T> ::templateClass(T a, T b) {
    x = a;
    y = b;
}

template <class T>
T templateClass<T>::bigger() {
    return (x > y ? x : y);
}

Finally in main.cpp I have

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

using namespace std;



int main() 
{
    templateClass<int> obj(12, 47);

    return 0;
}

In the end, I obtain an error unresolved external symbol "public: __thiscall templateClass::templateClass(int,int)" (??0?$templateClass@H@@QAE@HH@Z) referenced in function _main templateClass ...

Can you help me with explaing what is wrong and why the same works if put everything in one .cpp file without seperating?

zorro47
  • 221
  • 1
  • 11
  • 1
    You might insist but templates don't work that way. You're either going to have to put all the template code in a header file or give up on templates (or even C++). – john Jun 18 '19 at 12:55
  • Thank you for that, I thougt that class template can be "separated" the same way as normal classes. – zorro47 Jun 18 '19 at 12:59
  • 2
    I think it surprises everyone when they realise that they can't. – john Jun 18 '19 at 13:04
  • 1
    If you only have some fixed types that you will use with your template, then you can seperate them. See the question and answer (keyword: explicit template instantiation) –  Jun 18 '19 at 13:06
  • 3
    I recommend you to split your code in .h and .hpp, the .h containing the prototypes of your templated class, and the .hpp containing the implementation of your templated class. – Elias Jun 18 '19 at 13:07

0 Answers0