-1

Possible Duplicate:
Where to define C++ class member template function and functors that instantiate it?
inclusion of header files in case of templates

I am using class templates. I have several methods in my my class and if I define them in the .cpp file I am getting the linker error

error LNK2019: unresolved external symbol

Do all methods in template classes need to be defined in the header file? It makes my code look yucky but if it's the only way I am fine with it.

Community
  • 1
  • 1
James
  • 2,951
  • 8
  • 41
  • 55
  • Yes. Think about it: if you define `myClass::foo()` in `myClass.cpp`, and in `bar.cpp` some other code calls `myClass::foo()`, that function won't be defined in either `.o` file. – Beta Oct 01 '11 at 14:27

3 Answers3

4

Do all methods in template classes need to be defined in the header file?

Yes. But you can still factor out the parts that don't rely on template arguments and put those in a regular modules as ordinary functions or as a mixin class:

class NonTemplatedOpsMixin
{
    int bar();  // defined elsewhere
};

template <typename T>
class TemplatedStuff : private NonTemplatedOpsMixin
{
    T foo(T &x) { x += bar(); }
};
Fred Foo
  • 355,277
  • 75
  • 744
  • 836
1

Do all methods in template classes need to be defined in the header file?

Yes: for compiler to instantiate the template method definition, it must have the body of the method available to it.

It makes my code look yucky

One common technique is to have separate sections in your header:

template <typename T> class Foo {
  int Method();
};

// Other classes ...

// Now supply implementation details, not relevant to users of the class
template <typename T> int Foo<T>::Method()
{
  // implementation
}

// Other implementations

Another technique is to move bodies into a separate header file, e.g. foo-inl.h, and #include "foo-inl.h" from foo.h

Employed Russian
  • 199,314
  • 34
  • 295
  • 362
1

Do all methods in template classes need to be defined in the header file?

Yes

It makes my code look yucky but if it's the only way I am fine with it.

In that case, you can include the .cpp file in the header as:

//filename.h

template<typename T>
class whatever
{
     //...
};

#include "filename.cpp"  //write this at the bottom of filename.h

It's equivalent to providing all the template definitions in the header itself, but physically you've two files.

Alright, as the comment says, the build-system might not be happy with the extension .cpp, in that case, you can choose .h instead (or .hpp). It's safe now.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • 1
    Build systems might not be happy with a `.cpp` that is to be included in another file, though; I'd use a `detail/filename.hpp` for this. – Fred Foo Oct 01 '11 at 14:34