How to return NULL from a method in a template class

I have a method that 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; 
}

In some cases, it is not executed at run time, because some of the values can not be converted to NULL in C ++, for example std::string. What approach should I take here?

+5
source share
9 answers

If you want to return by value and don’t want to mess with return pointers and new / deleted, you can simply do the following:

template <typename T>
boost::optional<T> Test<T>::FindItem(T item)
{
    if(found)
        //return original value
    else
        return boost::none; 
}

and use it as follows:

Test<int> var;
boost::optional<int> V = var.FindItem(5)

if (V)
{
    // found
    int val = *V;
}
else
{
    // not found
}
+14
source

Here , Stroustrup gives a couple of arguments to avoid NULLin C ++:

  • 0, [ ]
  • , ++

, :

  • 0 ( ++ 0xwhatever) nullptr.

-, , , .

-, find() , . " " -.

+9

, , . , , . ( , , , , , ?)

. , / . a NULL / " ". , / . , . , - .

, , , / , std lib.

+6

T * non T

+2

, , bool:

template <typename T>
bool Test<T>::FindItem(T item)
{
    if (!found)
        return false;    
    item = <found item>;        
    return true; 
}
+2

, , ( ).

template <class T>
struct Make {
    static T Default()
    {
         return T();
    }
};


class not_default_constructable {
public:
    explicit not_default_constructable(int i) {}
};

// specialize for not_default_constructable     
template <>
struct Make <not_default_constructable> {
    static not_default_constructable Default()
    {
         return not_default_constructable(42);
    }
};
+1

, .

, , - . , .

, , , , , - . .

+1

T(). T sometype *, . T sometype, , , (std::string , int 0 ..).

0

, , NULL...

- :

class SomeError
{};
template <typename T>
    T Test<T>::FindItem(T item)
    {
        if(found) 
            //return original value, no problem here
        else
            throw(SomeError);
    }

Throwing an empty class doesn't cost anything ...

0
source

All Articles