Defining methods of class template
Jul 1, 2016 at 7:41am UTC
Hello. I'm trying to create a class template, but I cannot define its methods outside header file.
mtse.h:
1 2 3 4 5 6 7
template <typename T> class Stack
{
...
~Stack();
void push(const T &x);
...
};
mtse.cpp:
1 2 3 4 5
#include "mtse.h"
template <typename T> Stack<T>::~Stack()
{...}
template <typename T> void Stack<T>::push(const T &x)
{...}
Unfortunately, linker complains about "undefined reference to Stack<float>::push(float const&)" etc. Where is the problem?
Jul 1, 2016 at 8:11am UTC
Hi,
Templates have to be fully defined in the header file*. But read this:
https://isocpp.org/wiki/faq/templates#templates-defn-vs-decl
Hope this helps :+)
Btw, I use *.hpp for header files, it means a header file with c++ code in it, as opposed to a C header file. It's a bit pedantic, it doesn't seem to make much difference.
Last edited on Jul 1, 2016 at 8:13am UTC
Jul 1, 2016 at 12:08pm UTC
Thanks! I defined functions in the header file, and everything works fine.
Topic archived. No new replies allowed.