C++ Optional Return Values

After reading this article and being inspired, I decided to write a simple “optional” class that’s similar to boost::optional but lighter weight.  The idea is that often I write functions which should return a value but which might not have a value to return — and for those cases, I should be able to specify that the return type is optional.  In the calling code, I should have the ability to check that yes, a value was returned, and get the return value.  Here’s the entire content of the class:

template 
class optional
{
	private:
		T value;
		bool value_valid;
		
		bool is_initialized() const {return value_valid;}
		
	public:
		optional() : value(T()), value_valid(false) {}
		optional(T newvalue) : value(newvalue), value_valid(true) {}
		
		operator bool() const {return is_initialized();}
		
		T get() {assert(is_initialized());return value;}
		T get_or_default(T thedefault) {return is_initialized()?get():thedefault;}
};

Comments are closed.

Dev Journal and Project Hosting