0

I have a template class defined like this:

closedlist.h

template <typename T>
class ClosedList
{
public:
    // …

    bool isEmpty () const { return (size() == 0); }

    T first () const;
    T pop_first ();

    void push_back (const T &value);
    ClosedList& operator << (const T &value) { push_back(value); return *this; }

    int size () const { return _size; }

private:
    // …
};

Then, I have defined the functions in another file, like this:

closedlist.cpp

#include "closedlist.h"

template <typename T>
T ClosedList<T>::first () const
{
    // …
    T elem;
    // …
    return elem;
}

template <typename T>
T ClosedList<T>::pop_first ()
{
    // …
    T elem;
    // …
    return elem;
}

template <typename T>
void ClosedList<T>::push_back (const T &value)
{
    // …
}

If I change the method implementation, e.g. adding or removing the const behind it, g++ shows me an error that the method does not match any prototype. So I guess g++ finds the correct prototype for the function. But I get these errors:

obj/someclass.o: In function `SomeClass::doSomething()':
src/someclass.cpp:231: undefined reference to `ClosedList<Solution>::pop_first()'
src/someclass.cpp:326: undefined reference to `ClosedList<Solution>::push_back(Solution const&)'
obj/someclass.o: In function `ClosedList<Solution>::operator<<(Solution const&)':
include/closedlist.h:69: undefined reference to `ClosedList<Solution>::push_back(Solution const&)'

Note: I read Why can templates only be implemented in the header file? but since the question is from 2009 and I'm using C++11 I'm wondering if this is still like that. Other web pages showed like this one (sorry it's in German) shows code where the members are defined outside of the class definition.

Community
  • 1
  • 1
msrd0
  • 7,816
  • 9
  • 47
  • 82
  • "I read Why can templates only be implemented in the header file?" Then you have your answer. I don't know why you'd think this would have changed. The reason for it was never part of the spec, it's due to the implementation of templates in the compiler. – davmac Feb 07 '15 at 11:35
  • @davmac "Other web pages showed like [this one](http://de.wikibooks.org/wiki/C++-Programmierung/_Templates/_Klassentemplates#Definition_von_Membern) (sorry it's in German) shows code where the members are defined outside of the class definition." - That's why I asked – msrd0 Feb 07 '15 at 11:35
  • 1
    @msrd0 It's still like that, yes. Though some answers also describe techniques how to put the template implementations into a separate source file. – πάντα ῥεῖ Feb 07 '15 at 11:37
  • 1
    @msrd0 Although the members can be defined outside the class definition (as shown on the page you linked to), the definitions must still be visible when the template is instantiated (or at least when the relevant method is instantiated). Your second example doesn't actually contradict the "header file only" rule in any way. – davmac Feb 07 '15 at 11:50

0 Answers0