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?
std::string
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 }
Here , Stroustrup gives a couple of arguments to avoid NULLin C ++:
NULL
0
, :
nullptr
-, , , .
-, find() , . " " -.
, , . , , . ( , , , , , ?)
. , / . a NULL / " ". , / . , . , - .
, , , / , std lib.
T * non T
, , bool:
bool
template <typename T> bool Test<T>::FindItem(T item) { if (!found) return false; item = <found item>; return true; }
, , ( ).
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); } };
, .
, , - . , .
, , , , , - . .
T(). T sometype *, . T sometype, , , (std::string , int 0 ..).
T()
T
sometype *
sometype
int
, , 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 ...