Boost C++ Libraries Home Libraries People FAQ More

Next

Chapter 1. Boost.Optional

Fernando Luis Cacciola Carballal

Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

Table of Contents

Introduction
Problem
Solution
Tutorial
Optional return values
Optional data members
Bypassing unnecessary default construction
Discussion
Development
The models
The semantics
The Interface
Synopsis
Detailed Semantics
Examples
Optional return values
Optional local variables
Optional data members
Bypassing expensive unnecessary default construction
Optional references
Rebinding semantics for assignment of optional references
In-Place Factories
A note about optional<bool>
Exception Safety Guarantees
Type requirements
Dependencies and Portability
Optional Reference Binding
Acknowledgments

Class template optional is a wrapper for representing 'optional' (or 'nullable') objects who may not (yet) contain a valid value. Optional objects offer full value semantics; they are good for passing by value and usage inside STL containers. This is a header-only library.

Suppose we want to read a parameter form a config file which represents some integral value, let's call it "MaxValue". It is possible that this parameter is not specified; such situation is no error. It is valid to not specify the parameter and in that case the program is supposed to behave slightly different. Also suppose that any possible value of type int is a valid value for "MaxValue", so we cannot jut use -1 to represent the absence of the parameter in the config file.

This is how you solve it with boost::optional:

#include <boost/optional.hpp>

boost::optional<int> getConfigParam(std::string name);  // return either an int or a `not-an-int`

int main()
{
  if (boost::optional<int> oi = getConfigParam("MaxValue")) // did I get a real int?
    runWithMax(*oi);                                        // use my int
  else
    runWithNoMax();
}

Last revised: June 03, 2014 at 14:35:30 GMT


Next