C++ implementation of Option Design Pattern

Hi everybody,

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.

Any suggestions? Many thanks in advance.

Option.h:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#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.
		 */
		inline bool 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:

1
2
3
4
5
template <typename T>
class Option<T*>
{
...
}

Topic archived. No new replies allowed.