I'm using a template function searchByCriteria<T>
where I would like to be able to run the function using both a string
and a double
. I have a list of custom-defined objects that have string
and double
attributes, and I would like to be able to use this function to check the criteria value (of whatever type, entered by the user), to check for matches in the object attributes of the same type.
I.e. User enters a double value, check the object collection for matching double values. User enters a string value, check the object collection for matching string values.
The problem I am having is once the value is entered, it is passed to another template function to be checked against the elements in the list. And at this point, the T
object that is passed as a parameter, needs to be converted to either a double or a string to allow checking for matches.
Here is the code for this part:
//get a sub-list of transactions
//of all that match specified search criteria
template <typename T>
const TransactionList TransactionList::getTransactionsForSearchCriteria(T criteria) const {
//make a copy of list to avoid deleting existing data
TransactionList copy(*this);
//to have appropriate transactions added in
//then returned as copy
TransactionList ret;
//////////////////////////////////////////
//before checking for matches can start///
//must ID datatype of T instance//////////
//////////////////////////////////////////
//check all transactions until list empty
while (copy.size() > 0)
{
//check that criteria matches transaction attribute
if (/*converted criteria matches corresponding attribute*/)
{
//flag as match
}
}
}
As you can see, the parameter value criteria
needs to be converted back into a specific data type before the while loop can be entered to check for matches. I am at a slight loss as to how to do this, as I am not aware of any casting methods in C++ that would be useful in this situation.
The only thing I can think of would be something like:
try
{
//example method
convertToDouble(criteria);
}
catch (SomeKindOfNumberException ex)
{
//cannot be a double
//so must be string
convertToString(criteria);
}
Any help is greatly appreciated.
Thanks, Mark