Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return NULL from a method in a Template Class

Tags:

c++

templates

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?

like image 274
Aamir Avatar asked Sep 08 '09 09:09

Aamir


People also ask

How do you use return null?

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.

How do I return a nullable object in C#?

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.

What does return NULL return?

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.

Is class template and function template the same?

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.


1 Answers

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
}
like image 158
Xeor Avatar answered Oct 05 '22 14:10

Xeor