Using boost::optional can be an advantage in certain situation. In C++ it effectively works by being able to turn any datatype into a nullable value. It works much the same way as returning a null pointer to an object but without using a pointer. Instead this will work by being able to return an object which may or may not valid.
It is typically used to return a value from a function where the function may fail in certain situations. If you attempt to use the optional value which has not been set it will fail and the program will abort. This of course is also useful for debugging in order to catch issues sooner rather than later by accessing various variable that may not have valid values.
It can of course also be used to pass optional parameters to functions where you may not want to use operator overloading.
Here is an example of it converting an string to an int which will obviously fail on one of the strings.
#include <stdio.h>
#include <string>
#include <boost/optional.hpp>
boost::optional<int> func(const std::string &str)
{
boost::optional<int> value;
int tmp = 0;
if (sscanf(str.c_str(), "%d", &tmp) == 1)
value.reset(tmp);
return value;
}
int main(int argc, char **argv)
{
boost::optional<int> v1 = func("31245");
boost::optional<int> v2 = func("hello");
if (v1)
printf("%d\n", v1.get());
else
printf("v1 not valid\n");
if (v2)
printf("%d\n", v2.get());
else
printf("v2 not valid\n");
return 0;
}
Did You find this page useful?
Yes
No