Trouble With Template Classes in C++

Sage
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:

Code:
/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/Spyscroller.build/Debug/Spyscroller.build/Objects-normal/ppc/Widget.o reference to undefined SimEngine::Vector2D<int>::Vector2D(SimEngine::Vector2D<int> const&)
/Users/nickgravelyn/Documents/Xcode/Spyscroller/build/Spyscroller.build/Debug/Spyscroller.build/Objects-normal/ppc/Widget.o 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:

Code:
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
Luminary
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
Sage
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
Member
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
DoG
Moderator
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
  C++ Interlocking Classes merrill541 1 2,658 Jan 25, 2009 08:43 PM
Last Post: akb825
  Noob: Accessing Structures from Cocoa Classes MikeC 15 7,390 Oct 19, 2007 02:42 PM
Last Post: MikeC
  Trouble with template classes ermitgilsukaru 2 2,695 Aug 11, 2006 02:00 PM
Last Post: ermitgilsukaru
  Template specialization of a method Fenris 4 3,145 Jul 11, 2005 02:45 PM
Last Post: OneSadCookie
  Noob: Copying Classes hangt5 3 3,541 Mar 9, 2005 12:52 PM
Last Post: codemattic