I have a C++ method findID that uses templates, and I want to be able to run a condition in this method based on the input type. The template parameter U will either be of type int or type string. I want to run a different condition based on the type of ID.
The code I have is follows:
template <typename S>
template <typename U>
S * findID(U ID){
for (typename vector<S*>::collectionsIter element = collection.begin() ; element != collection.end(); ++element)
if((*element)->getID() == ID) return *element;
return NULL;
}
I want my code to do the following:
template <typename S>
template <typename U>
S * findID(U ID){
***if ID is an int:
for (typename vector<S*>::collectionsIter element = collection.begin() ; element != collection.end(); ++element)
if((*element)->getID() == ID) return *element;
***if ID is a string:
for (typename vector<S*>::collectionsIter element = collection.begin() ; element != collection.end(); ++element)
if((*element)->getStringID() == ID) return *element;
***else
return NULL;
}
The reason that I want to do this is because I want to be able to compare string variables of ID to the string method of getStringID(), and the int variables of ID to the int method of getID(). In addition I do not want to break these up into separate methods, so I am trying to use templates and these conditions to refactor it into 1 method.