I have a method which looks like this:
template <typename T>
T Test<T>::FindItem(T item)
{
if(found)
//return original value, no problem here
else
//I want to return NULL here, like:
return NULL;
}
This fails in certain cases at runtime because some of the values can't be converted to NULL in C++ e.g., std::string
. What approach should I follow here?
Returning null is usually the best idea if you intend to indicate that no data is available. An empty object implies data has been returned, whereas returning null clearly indicates that nothing has been returned.
So, to return a null or default value from a generic method we can make use default(). default(T) will return the default object of the type which is provided.
A function that returns a null reference achieves neither goal. Returning null is like throwing a time bomb into the software. Other code must a guard against null with if and else statements. These extra statements add more complexity to the software.
The difference is, that the compiler does type checking before template expansion. The idea is simple, source code contains only function/class, but compiled code may contain multiple copies of the same function/class. Function Templates We write a generic function that can be used for different data types.
If you want to return by value and don't want to mess with returning pointers and new/delete, you can just do like this:
template <typename T>
boost::optional<T> Test<T>::FindItem(T item)
{
if(found)
//return original value
else
return boost::none;
}
and use it this way:
Test<int> var;
boost::optional<int> V = var.FindItem(5)
if (V)
{
// found
int val = *V;
}
else
{
// not found
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With