I am trying to realize the Option design pattern (from http://www.codeproject.com/Articles/17607/The-Option-Pattern) in C++. I am trying it with usage of C++ templates, but somehow got stuck, because I can't check against null if the template parameter T is a primitive datatype. My current source code is shown below.
#ifndef OPTION_H_
#define OPTION_H_
template <typename T>
class Option
{
private:
bool _valueIsPresent;
T _value;
public:
/**
* Create a new option without any value.
*/
Option()
{
_valueIsPresent = false;
}
/**
* Create a new option containing the given value.
* @param The value to store in the option.
*/
Option(T value)
{
// VALUE MUST BE PROVIDED
if (value == 0)
{
// THROW EXCEPTION HERE
}
_value = value;
_valueIsPresent = true;
}
/**
* Gets information whether there is a value present.
* @return Returns true if value is present, false otherwise.
*/
inlinebool isValuePresent() { return _valueIsPresent; }
/**
* Gets the value.
* Note: If no value is present and this method is called, an InvalidOperationException exception is thrown.
*/
T getValue()
{
// Prevent access to non existing value
if (!_valueIsPresent)
{
throw InvalidOperationException("Tried to get a non existing value.");
}
return _value;
}
};
#endif /* OPTION_H_ */
because I can't check against null if the template parameter T is a primitive datatype.
What? For primitive type (aka POD) you can always check against 0. When you have complex types you cannot.
What you can do is:
1 2 3 4 5 6
Option() : _value() // This initializes _value with a default value (in case of POD 0)
{
...
_value = T(); // This initializes _value with a default value (in case of POD 0)
if(_value == T()) // This compares POD's with 0 and other types with the default object
If you want to enforce a pointer to be bot null(but why the user would not be able to pass a null pointer? I think an option on a null pointer makes sense) you can specialize the class for pointer types: