I have been trying to use boost optional for a function that could either return an object or a null and I cant figure it out. Here is what I have so far. Any suggestions on how to resolve this issue would be appreciated.
class Myclass
{
public:
int a;
};
boost::optional<Myclass> func(int a) //This could either return MyClass or a null
{
boost::optional<Myclass> value;
if(a==0)
{
//return an object
boost::optional<Myclass> value;
value->a = 200;
}
else
{
return NULL;
}
return value;
}
int main(int argc, char **argv)
{
boost::optional<Myclass> v = func(0);
//How do I check if its a NULL or an object
return 0;
}
Update:
This is my new code and I am getting a compiler error at value = {200};
class Myclass
{
public:
int a;
};
boost::optional<Myclass> func(int a)
{
boost::optional<Myclass> value;
if(a == 0)
value = {200};
return value;
}
int main(int argc, char **argv)
{
boost::optional<Myclass> v = func(0);
if(v)
std::cout << v -> a << std::endl;
else
std::cout << "Uninitilized" << std::endl;
std::cin.get();
return 0;
}