How to return NULL from a method in a Template Class

c++, templates

Solution

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
}

Problem

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?

Original source