Extending stl vectors with template functions

Apr 29, 2010 at 11:37am
Dear all,
I'm creating a set of functions to handle stl vectors. Some are useful for achieving my goals. I'm coding some other just for fun. But after some coding I see I cannot compile them propperly.

One example would be a vector print function which prints all the elements of a vector of an arbitrary type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
template <typename T>
void printVector (T &v1);

--- vecTools.cpp---
#include "vecTools.h"

template <typename T >
void printVector ( T &v1){
	cout<<"[ ";
	for (unsigned int i =0; i < v1.size(); i++){
		cout<<v1[i]<<", ";
	}
	cout<<"] \n";
}


The answer of the g++ compiler is as follows:
1
2
3
../src/Tools/Test/main.cpp:39: undefined reference to `void printVector<DummyObject>(std::vector<DummyObject, std::allocator<DummyObject> >&)'
collect2: ld returned 1 exit status
make: *** [core_iteration1] Error 1 


Do you know how can one fix this? Maybe it's impossible?

Many thanks!!
Víctor

Apr 29, 2010 at 12:08pm
That template is not for vectors, add the vector stuff, like this:
1
2
template <typename T >
void printVector ( const std::vector<T> &v1){
BTW, you'll have to keep the implementation in the header when you use templates
Last edited on Apr 29, 2010 at 12:09pm
Apr 29, 2010 at 12:17pm
Yep, sorry, I pasted the wrong code. I also tested without the vector definition (and with thousand other combinations). But the key was in the implementation thing!!!

Thank you very much man!! I was really stuck here!!
Apr 29, 2010 at 5:31pm
std::vector<> has other template parameters besides the contained type. Your printVector
does not account for them.



May 3, 2010 at 10:28am
uh.. btw, should I code everything in a .cpp file or in a .h file? I'm interested in following the 'de facto' standards :)

Thanks!
May 3, 2010 at 11:57am
For templates, everything in the header
Topic archived. No new replies allowed.