Trouble With Template Classes in C++

Posts: 1,066
Joined: 2004.07
Post: #1
I'm trying to use a template class for a 2D vector but I'm having trouble with a few linker errors:

/usr/bin/ld: Undefined symbols:
SimEngine::Vector2D<int>::Vector2D(SimEngine::Vector2D<int> const&)
SimEngine::Vector2D<int>::operator=(SimEngine::Vector2D<int> const&)
/Users/nickgravelyn/Documents/Xcode/Spyscroller/build/ reference to undefined SimEngine::Vector2D<int>::Vector2D(SimEngine::Vector2D<int> const&)
/Users/nickgravelyn/Documents/Xcode/Spyscroller/build/ reference to undefined SimEngine::Vector2D<int>::operator=(SimEngine::Vector2D<int> const&)
collect2: ld returned 1 exit status

So I checked and sure enough I have those methods defined:

template<class E>
Vector2D<E>::Vector2D( const Vector2D<E> &v ) : x( v.x ), y( v.y ) {

template<class E>
Vector2D<E>& Vector2D<E>::operator = ( const Vector2D<E> &v ) {
    x = v.x;
    y = v.y;
    return ( *this );

Am I doing something incorrectly? I can easily put more code up if necessary, but I figured this was all that would be needed.
Quote this message in a reply
Posts: 5,143
Joined: 2002.04
Post: #2
Due to the way templates work in C++, all the code must be in or included from the header file. It's usual just to put it all inline in the class declaration, but it's possible (if weird) to #include the .cpp file at the bottom of the header.
Quote this message in a reply
Posts: 1,066
Joined: 2004.07
Post: #3
Hm. I don't want to put all of it in the header, but I think I will just because including a cpp file seems wrong.
Quote this message in a reply
Posts: 45
Joined: 2006.11
Post: #4
One convention I've seen (not sure if it is "correct" or not) is to put the implementation of a template class in a .hpp file, and include it in the header, rather than include a .cpp file, which someone may confuse as a file that needs to be compiled and linked, which it wouldn't.
Quote this message in a reply
Posts: 869
Joined: 2003.01
Post: #5
Template implementations belong in a header file, be it .h or .hpp to your liking.
Quote this message in a reply
Post Reply 

Possibly Related Threads...
Thread: Author Replies: Views: Last Post
  Standard C++ Carbon Application Template AdrianM 2 4,943 Jun 29, 2009 04:51 AM
Last Post: AdrianM
  C++ Interlocking Classes merrill541 1 3,857 Jan 25, 2009 08:43 PM
Last Post: akb825
  Noob: Accessing Structures from Cocoa Classes MikeC 15 11,634 Oct 19, 2007 02:42 PM
Last Post: MikeC
  Apple "OpenGL Game Template" OneSadCookie 34 26,384 Sep 5, 2006 02:47 PM
Last Post: OneSadCookie
  Trouble with template classes ermitgilsukaru 2 4,247 Aug 11, 2006 02:00 PM
Last Post: ermitgilsukaru