Reputation: 1174
I would like to do a function that manipulates a vector in order to select one, and return it. (The best would be to return an iterator that points that selection.)
Alright, I have this code here in my header :
class Ecran { // That means Screen in french :P
// Other definitions...
template<typename T>
static T* SelectFrom(vector<T> & v);
}
Implementation :
template <class T>
T* Ecran::SelectFrom(vector<T> &v){
int max = v.size();
cout << "Veuillez selectionner un objet parmis les suivants:" << endl << endl;
cout << "0) Aucun" << endl;
for (int i = 1; i <= max; i++){
cout << i << ") " << v[i-1] << endl;
}
bool isValid = false;
string raw;
int input;
while (!isValid){
raw = GetWord();
input = atoi(raw.c_str());
if( (input >= 0) && (input <= max)){
isValid = true;
}
}
if (input == 0){
return 0;
}
return & (v[input -1]);
}
So, here's the problem : when I use it, compiler tells me that :
undefined reference to `Club* Ecran::SelectFrom(std::vector >&)
I use it like that :
Club * toDel = Ecran::SelectFrom(_clubs);
That's it, any help would be greatly appreciated. Furthermore, would there be a way to do this but returns an iterator instead of a point to T ?
Thank you already.
Upvotes: 3
Views: 2097
Reputation: 58685
This function is a template, so make sure its definition is in the header file.
For returning an iterator, std::vector<T>::iterator
, rather than a pointer:
return v.begin() + input - 1;
Upvotes: 4
Reputation: 372972
The problem you're getting is a linker error, and if I had to guess I would assume that your problem is that you've split up your implementation into a .h/.cpp pair. For regular C++ classes, this is the correct approach, but when dealing with templates you must put all of the code, including the implementation, into the header file.
The reason for this has to do with the C++ compilation and linking model and how it plays with templates. With a regular class, the compiler can generate code for each .cpp file separately and then link all of the code together to resolve external links. The problem with this approach as applied to templates, though, is that templates aren't code; they're patterns for code, and when you compile the actual template itself no code is generated. Code for templates is only generated when the template is instantiated, and when this happens the code to be instantiated must be visible. Consequently, if you compile a .cpp file containing a template class implementation, then the compiler won't be able to see that code when the template is actually used, and thus won't generate any instantiations of that code, hence the linker error.
Upvotes: 9