Trouble With Template Classes in C++
I'm trying to use a template class for a 2D vector but I'm having trouble with a few linker errors:
So I checked and sure enough I have those methods defined:
Am I doing something incorrectly? I can easily put more code up if necessary, but I figured this was all that would be needed.
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 statusSo 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.
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.
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.
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.
Possibly Related Threads...
| Thread: | Author | Replies: | Views: | Last Post | |
| C++ Interlocking Classes | merrill541 | 1 | 2,206 |
Jan 25, 2009 08:43 PM Last Post: akb825 |
|
| Noob: Accessing Structures from Cocoa Classes | MikeC | 15 | 6,582 |
Oct 19, 2007 02:42 PM Last Post: MikeC |
|
| Trouble with template classes | ermitgilsukaru | 2 | 2,345 |
Aug 11, 2006 02:00 PM Last Post: ermitgilsukaru |
|
| Template specialization of a method | Fenris | 4 | 2,770 |
Jul 11, 2005 02:45 PM Last Post: OneSadCookie |
|
| Noob: Copying Classes | hangt5 | 3 | 3,162 |
Mar 9, 2005 12:52 PM Last Post: codemattic |
|

