I am searching through a vector of unique_ptr's to an object. The object is resolved, for instance, by a user entering a name. Hence a function of the sort:
std::unique_ptr<obj> const& objectForName(std::string name) {
std::vector<std::unique_ptr<obj>>::iterator it;
it = std::find_if(objVec.begin(), objVec.end(), [name](const std::unique_ptr<obj>& object) -> bool {return object->getName() == name; });
if (it != objVec.end())
return *it;
else
throw(Some_Exception("Exception message"));
}
I would like to reuse this function in the case when adding an object to this vector. Function should call this and in the case of not finding it return something that can be checked by the calling function, instead of throwing an exception. The calling function can throw the exception on checking the return value. My question is what can be returned that calling function can be checked?
Just return a pointer:
obj const* objectForName( std::string const& name )
{
std::vector<std::unique_ptr<obj>>::iterator results
= std::find_if(
objVec.begin(),
objVec.end(),
[&]( std::unique_ptr<obj> const& object ) {
return object->getName == name; } );
return results != objVec.end()
? results->get()
: nullptr;
}
You can also use something like boost::optional here:
boost::optional<std::unique_ptr<obj> const&> objectForName(std::string name);
std::vector<std::unique_ptr<obj>>::iterator it;
it = std::find_if(objVec.begin(), objVec.end(), [name](const std::unique_ptr<obj>& object) -> bool {return object->getName() == name; });
if (it != objVec.end())
return *it;
else
return boost::none;
}
Usage:
const auto val = objectForName("bla1");
if (val) std::cout << "ok: " << val.get()->getName();
else std::cout << "none";
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