0

I am writing a template class Foo as follows

Foo.h

template <class T>
class Foo{
public:
    Foo(int m, int n, T x);
private:
    int _m;
    int _n;
    T _x
};

Foo.cpp

template <class T>
Foo<T>::Foo(int m, int n, T x):_m(m), _n(n), _x(x){}

Now, when I try to initialize the class, I get a compilation errors

int main()
{
    Foo<int> a (2,3, 4);
}

Errors:

Invalid arguments '

undefined reference to `Foo::~Foo()'

undefined reference to `Foo::Foo(int, int, int)'

Is there any mistakes in the .h or the .cpp files? or should I initialize the class in a different way?

Student
  • 3
  • 2
  • Did you `#include "Foo"` in your `main.cpp`? – Fureeish Dec 23 '17 at 01:47
  • Yes, I did include Foo.h in the main.cpp – Student Dec 23 '17 at 01:50
  • Then you should go to the question which yours was flagged as duplicate to and see *"Why can templates only be implemented in the header file?*" – Fureeish Dec 23 '17 at 01:50
  • I see the question marked as duplicate to another question but I don't see the connection. Does that mean, I need to implement the class fully in the Foo.h and just delete the Foo.cpp? – Student Dec 23 '17 at 01:52
  • No, you don't have to implement the class fully in `Foo.h`. Just the templates – Fureeish Dec 23 '17 at 01:52
  • 1
    Correct, templates must be visible in every translation unit they are referenced. After you learn and fully understand what templates are, how they work, and how your C++ compiler implements templates, you may then read your compiler's documentation to see if your compiler offers a way to explicitly instantiate templates in a single translation unit. But this would be a compiler-specific feature. But as you're learning how to use templates, the only way you'll be able to use them is to define them completely in their header file. – Sam Varshavchik Dec 23 '17 at 02:09

0 Answers0