In the old days, you might have a function like this:
const char* find_response(const char* const id) const;
If the item could not be found
boost::optional. It was specifically designed for this kind of situation.
Note, it will be included in upcoming C++14 standard as Update: After reviewing national body comments to N3690, std::optional.std::optional was voted out from C++14 working paper into a separate Technical Specification. It is not a part of the draft C++14 as of n3797.
Compared to std::unique_ptr, it avoids dynamic memory allocation, and expresses more clearly its purpose. std::unique_ptr is better for polymorphism (e.g. factory methods) and storing values in containers, however.
Usage example:
#include
#include
#include
class A
{
private:
std::string value;
public:
A(std::string s) : value(s) {}
boost::optional find_response(const std::string& id) const
{
if(id == value)
return std::string("Found it!");
else
return boost::none;
//or
//return boost::make_optional(id == value, std::string("Found it!"));
}
//You can use boost::optional with references,
//but I'm unfamiliar with possible applications of this.
boost::optional get_id() const
{
return value;
}
};
#include
int main()
{
A a("42");
boost::optional response = a.find_response("42"); //auto is handy
if(response)
{
std::cout << *response;
}
}