Optional Variables

Optional variables are a useful way of representing a "don't know", "use default" or "invalid" state.  An optional variable is basically a container that can hold zero or one elements.  When the optional variable is "empty" it represents the  "don't know", "use default" or "invalid" state otherwise it contains an actual value/object.

You can download the implementation here (v1.0.1).  You also need vecarray.h.

Here is an example of usage:

int main()
{
    lib::optional<bool> wear_hat;

    std::cout << "Wear a hat tomorrow? (yes/no/maybe) ";
    std::string response;
    std::cin >> response;

    if (response == "yes")
        wear_hat = true;
    else if (response == "no")
        wear_hat = false;

    if (wear_hat.invalid())
        std::cout << "I will wear a hat tomorrow if it looks like rain." << std::endl;
    else if (*wear_hat)
        std::cout << "I am going to wear a hat." << std::endl;
    else if (!*wear_hat)
        std::cout << "I am not going to wear a hat." << std::endl;

    return 0;
}

As well as the methods valid() and invalid() there is also a conversion to bool operator so instead of writing if (wear_hat.invalid()) one could have written if (!wear_hat) however this does look slightly confusing and unclear.  In providing a conversion to bool operator the "safe bool idiom" which is advocated by some is not being used but feel free to change this if you see fit.

Possibly the best use of optional variables is in the return types of functions.  With optional variables functions can return either a valid value or an invalid error instead of the old fashioned returning of -1 or the new fangled throwing of an exception.

Obviously any type of object can be used in an optional variable, not just bool.

Boost provides its own version of optional variables.


You can e-mail comments to the author.

Back to project page