2.6.0
Freundlich's C++ toolkit
Classes | Typedefs | Functions
fcppt.optional

Description

A class that makes values optional.

Motivation

Often it is necessary to distinguish between having a value and having none. This includes operations that might return no result, for example looking for an element in a container. Also, in a lot of situations, data may be absent, for example a tree might have a parent or it might have none. Values that may be nothing are common in C++ but are not handled consistently. This includes special values like std::string::npos, nullptr or end iterators. Modelling optionals explicitly has several advantages. Consider the following example:

void
optional_example_bad(
unsigned
> const _opt
)
{
if(
_opt.has_value()
)
<< _opt.get_unsafe()
<< '\n';
else
<< "No value\n";
}

First of all, the example makes it clear that the function can deal with an unsigned int or nothing at all. However, using optionals in this way makes them no safer than using pointers that may be null. In order to fix this, we must avoid calling get_unsafe at all. The most basic operation that does this is called maybe which acts on the two different cases.

void
optional_example_good(
unsigned
> const _opt
)
{
_opt,
[]{
<< "No value\n";
},
[](
unsigned const _val
)
{
<< _val
<< '\n';
}
);
}

Notice that by using maybe, the code checking if the optional has a value and the code dereferencing the optional are both gone.

Design

The goal of fcppt::optional, in contrast to boost::optional (and sadly C++17's std::optional), is to avoid pointer semantics and use explicit conversions only. The key differences include:

Optional References

Instead of implementing optional references directly, fcppt offers fcppt::optional::reference which is a typedef to fcppt::optional::object<fcppt::reference<T>>. The reason behind this is that code that acts on optionals might make use of references itself. For example it is not uncommon to pass the object held by an optional to functions like fcppt::optional::maybe_void by (const) reference, which can be used to change the object or to pass its address along.

typedef
int
>
optional_int;
void
set_ref(
optional_int _opt_ref
)
{
_opt_ref,
[](
int &_ref
)
{
_ref = 42;
}
);
}

On the other hand, if an optional holds a reference it does not hold the actual object, so changing the object behind the reference or passing the reference along has different semantics.

typedef
int
>
optional_int_ref;
void
set_ref2(
optional_int_ref const _opt_ref
)
{
_opt_ref,
[](
int
> const _ref
)
{
_ref.get() = 42;
}
);
}

Using fcppt::reference for optional references clearly distinguishes these two cases.

Common Operations

fcppt::optional::maybe is the most basic function that operates on optionals.

fcppt::optional::map lifts a function to a function on optionals:

optional_string const value2{
optional_uint{3u},
[](
unsigned const _val
)
{
return
_val
);
}
)
};
std::cout << (value == optional_string{"3"}) << '\n';

The more general fcppt::optional::bind returns the function's result directly:

typedef
unsigned
>
optional_uint;
typedef
>
optional_string const value{
optional_uint{3u},
[](
unsigned const _val
)
{
return
_val
)
);
}
)
};
std::cout << (value == optional_string{"3"}) << '\n';

Another commonly used function is fcppt::optional::from:

typedef
unsigned
>
optional_uint;
unsigned const value{
optional_uint(),
[]{
return
42u;
}
)
};
std::cout << (value == 42u) << '\n';

Header files

Header file Description
object_fwd.hpp Contains optional's declaration.
object_decl.hpp Contains optional's definition.
object_impl.hpp Contains the definition of optional's member functions.
object.hpp Includes object_impl.hpp and comparison.hpp.
alternative.hpp Contains fcppt::optional::alternative.
apply.hpp Contains fcppt::optional::apply.
assign.hpp Contains fcppt::optional::assign.
bind.hpp Contains fcppt::optional::bind.
cat.hpp Contains fcppt::optional::cat.
combine.hpp Contains fcppt::optional::combine.
comparison.hpp Contains operator==, operator!= and operator< .
const_cast.hpp Contains fcppt::optional::const_cast_.
copy_value.hpp Contains fcppt::optional::copy_value.
deref.hpp Contains fcppt::optional::deref.
dynamic_cast.hpp Contains fcppt::optional::dynamic_cast_.
filter.hpp Contains fcppt::optional::filter.
from.hpp Contains fcppt::optional::from.
from_pointer.hpp Contains fcppt::optional::from_pointer.
join.hpp Contains fcppt::optional::join.
make.hpp Contains fcppt::optional::make.
map.hpp Contains fcppt::optional::map.
maybe.hpp Contains fcppt::optional::maybe.
maybe_multi.hpp Contains fcppt::optional::maybe_multi.
maybe_void.hpp Contains fcppt::optional::maybe_void.
maybe_void_multi.hpp Contains fcppt::optional::maybe_void_multi.
output.hpp Contains operator<< .
reference_fwd.hpp Contains the fcppt::optional::reference typedef.
reference.hpp Includes reference_fwd.hpp and object_impl.hpp.
static_cast.hpp Contains fcppt::optional::static_cast_.
to_exception.hpp Contains fcppt::optional::to_exception.

Classes

struct  fcppt::optional::nothing
 A polymorphic empty optional. More...
 
class  fcppt::optional::object< T >
 A class that makes values optional. More...
 

Typedefs

template<typename T >
using fcppt::optional::reference = fcppt::optional::object< fcppt::reference< T > >
 Optional of a reference. More...
 

Functions

template<typename Optional , typename Function >
std::remove_reference< Optional >::type fcppt::optional::alternative (Optional &&_optional1, Function const &_optional2)
 Returns the first optional if it is not nothing. More...
 
template<typename Function , typename... Optionals>
auto fcppt::optional::apply (Function const &_function, Optionals &&... _optionals) -> fcppt::optional::object< decltype(_function(fcppt::move_if_rvalue< Optionals >(_optionals.get_unsafe())...)) >
 Applies a function to multiple optionals or returns nothing. More...
 
template<typename Element , typename Arg >
Element & fcppt::optional::assign (fcppt::optional::object< Element > &_optional, Arg &&_arg) FCPPT_PP_WARN_UNUSED_RESULT
 Assigns an optional and returns a reference to the optional's contents. More...
 
template<typename Optional , typename Function >
auto fcppt::optional::bind (Optional &&_source, Function const &_function) -> typename std::remove_reference< decltype(_function(fcppt::move_if_rvalue< Optional >(_source.get_unsafe()))) >::type
 Converts an optional of one type to another. More...
 
template<typename TargetContainer , typename Source >
TargetContainer fcppt::optional::cat (Source &&_source)
 Removes empty optionals from a range. More...
 
template<typename Optional , typename Function >
auto fcppt::optional::combine (Optional &&_optional1, Optional &&_optional2, Function const &_function) -> fcppt::optional::object< decltype(_function(fcppt::move_if_rvalue< Optional >(_optional1.get_unsafe()), fcppt::move_if_rvalue< Optional >(_optional2.get_unsafe()))) >
 Combines two optionals. More...
 
template<typename T >
bool fcppt::optional::operator== (fcppt::optional::object< T > const &_a, fcppt::optional::object< T > const &_b)
 Compares two optionals for equality. More...
 
template<typename T >
bool fcppt::optional::operator!= (fcppt::optional::object< T > const &_a, fcppt::optional::object< T > const &_b)
 Compares two optionals for inequality. More...
 
template<typename T >
bool fcppt::optional::operator< (fcppt::optional::object< T > const &_a, fcppt::optional::object< T > const &_b)
 Compares two optionals lexicographically. More...
 
template<typename Result , typename Arg >
fcppt::optional::reference< Result > fcppt::optional::const_cast_ (fcppt::optional::reference< Arg > const &_optional)
 Converts an optional reference using const_cast More...
 
template<typename Type >
fcppt::optional::object< typename std::remove_cv< Type >::type > fcppt::optional::copy_value (fcppt::optional::reference< Type > const &_opt)
 Copies the value of an optional reference. More...
 
template<typename Element >
fcppt::optional::object< fcppt::reference< typename std::remove_reference< decltype(*std::declval< Element >)) >::type >> fcppt::optional::deref (fcppt::optional::object< Element > const &_optional)
 Dereferences the contents of an optional. More...
 
template<typename Result , typename Arg >
fcppt::optional::reference< Result > fcppt::optional::dynamic_cast_ (fcppt::optional::reference< Arg > const &_optional)
 Converts an optional reference using dynamic_cast More...
 
template<typename Optional , typename Function >
std::decay< Optional >::type fcppt::optional::filter (Optional &&_source, Function const &_function)
 Filters an optional. More...
 
template<typename Optional , typename Default >
std::result_of< Default()>::type fcppt::optional::from (Optional &&_optional, Default const _default)
 Returns the value contained in an optional or a default value. More...
 
template<typename T >
fcppt::optional::reference< T > fcppt::optional::from_pointer (T *const _pointer)
 Creates an optional reference from a pointer. More...
 
template<typename Optional >
std::remove_cv< typename std::remove_reference< Optional >::type >::type::value_type fcppt::optional::join (Optional &&_source)
 Removes one layer of optionals. More...
 
template<typename Type >
fcppt::optional::object< typename std::decay< Type >::type > fcppt::optional::make (Type &&_value)
 Wraps a value into an optional. More...
 
template<typename Function >
fcppt::optional::object< typename std::result_of< Function() >::type > fcppt::optional::make_if (bool const _is_set, Function const &_function)
 Creates an optional depending on a boolean. More...
 
template<typename Optional , typename Function >
auto fcppt::optional::map (Optional &&_source, Function const &_function) -> fcppt::optional::object< typename std::remove_cv< decltype(_function(fcppt::move_if_rvalue< Optional >(_source.get_unsafe()))) >::type >
 Maps over an optional using a function. More...
 
template<typename Optional , typename Default , typename Transform >
std::result_of< Default()>::type fcppt::optional::maybe (Optional &&_optional, Default const _default, Transform const _transform)
 Transforms an optional value or returns a default value. More...
 
template<typename Default , typename Transform , typename... Optionals>
std::result_of< Default()>::type fcppt::optional::maybe_multi (Default const _default, Transform const _transform, Optionals &&... _optionals)
 Transforms multiple optional values or returns a default value. More...
 
template<typename Optional , typename Transform >
void fcppt::optional::maybe_void (Optional &&_optional, Transform const _transform)
 Transforms an optional value or does nothing. More...
 
template<typename... Optionals, typename Transform >
void fcppt::optional::maybe_void_multi (Transform const _transform, Optionals &&... _optionals)
 Transforms optional values or does nothing. More...
 
template<typename Type , typename Ch , typename Traits >
std::basic_ostream< Ch, Traits > & fcppt::optional::operator<< (std::basic_ostream< Ch, Traits > &_stream, fcppt::optional::object< Type > const &_opt_value)
 Outputs an optional to a basic_ostream. More...
 
template<typename Result , typename Arg >
fcppt::optional::reference< Result > fcppt::optional::static_cast_ (fcppt::optional::reference< Arg > const &_optional)
 Converts an optional reference using static_cast More...
 
template<typename Container , typename Optional >
Container fcppt::optional::to_container (Optional &&_source)
 Puts the value of an optional into a container or returns an empty container. More...
 
template<typename Optional , typename MakeException >
auto fcppt::optional::to_exception (Optional &&_optional, MakeException const _make_exception) -> decltype(fcppt::move_if_rvalue< Optional >(_optional.get_unsafe()))
 Returns the value contained in an optional or throws an exception. More...
 
template<typename T >
T * fcppt::optional::to_pointer (fcppt::optional::reference< T > const _optional)
 Converts an optional reference to a pointer. More...
 

Typedef Documentation

◆ reference

template<typename T >
using fcppt::optional::reference = typedef fcppt::optional::object< fcppt::reference< T > >

Optional of a reference.

Function Documentation

◆ alternative()

template<typename Optional , typename Function >
std::remove_reference< Optional>::type fcppt::optional::alternative ( Optional &&  _optional1,
Function const &  _optional2 
)

Returns the first optional if it is not nothing.

If _optional1 is not nothing, the result is _optional1, otherwise the result of _optional2 is returned.

Template Parameters
FunctionA function callable as Optional ().

◆ apply()

template<typename Function , typename... Optionals>
auto fcppt::optional::apply ( Function const &  _function,
Optionals &&...  _optionals 
) -> fcppt::optional::object< decltype( _function( fcppt::move_if_rvalue< Optionals >( _optionals.get_unsafe() )... ) ) >
inline

Applies a function to multiple optionals or returns nothing.

If _optionals, o_1,...,o_n are set to x_1,...,x_n, then _function(x_1,...,x_n) is returned. Otherwise, the empty optional is returned.

Template Parameters
FunctionA function callable as R (Optionals::value_type...) where R is the result type
OptionalsA parameter pack of optionals

◆ assign()

template<typename Element , typename Arg >
Element & fcppt::optional::assign ( fcppt::optional::object< Element > &  _optional,
Arg &&  _arg 
)
inline

Assigns an optional and returns a reference to the optional's contents.

Assign _arg to _optional and returns a reference to _arg.

◆ bind()

template<typename Optional , typename Function >
auto fcppt::optional::bind ( Optional &&  _source,
Function const &  _function 
) -> typename std::remove_reference< decltype( _function( fcppt::move_if_rvalue< Optional >( _source.get_unsafe() ) ) ) >::type
inline

Converts an optional of one type to another.

Converts _source into the optional type returned by _function. If _source is empty, the empty optional is returned. Otherwise, _source is dereferenced and the result from applying _function is returned.

Parameters
_sourceThe optional to convert
_functionThe function to apply to the value inside _source. It must accept a type of Source.

◆ cat()

template<typename TargetContainer , typename Source >
TargetContainer fcppt::optional::cat ( Source &&  _source)

Removes empty optionals from a range.

For every element e in _source, if e is set to x, then x is inserted into the target container.

Template Parameters
SourceMust be a container of optionals
TargetContainerMust be a container whose value type matches that of the optionals from Source

◆ combine()

template<typename Optional , typename Function >
auto fcppt::optional::combine ( Optional &&  _optional1,
Optional &&  _optional2,
Function const &  _function 
) -> fcppt::optional::object< decltype( _function( fcppt::move_if_rvalue< Optional >( _optional1.get_unsafe() ), fcppt::move_if_rvalue< Optional >( _optional2.get_unsafe() ) ) ) >

Combines two optionals.

If _optional1 is set to x1 and _optional2 is set to x2, then Optional(_function(x1, x2)). Otherwise, if at least one optional is set, that optional is returned.

◆ const_cast_()

template<typename Result , typename Arg >
fcppt::optional::reference< Result> fcppt::optional::const_cast_ ( fcppt::optional::reference< Arg > const &  _optional)

Converts an optional reference using const_cast

Template Parameters
ResultA non reference type of the result
ArgA non reference type of the argument

Converts _optional using const_cast to a Result & if _optional.has_value() is true. Otherwise, the empty optional will be returned.

◆ copy_value()

template<typename Type >
fcppt::optional::object< typename std::remove_cv< Type >::type> fcppt::optional::copy_value ( fcppt::optional::reference< Type > const &  _opt)

Copies the value of an optional reference.

◆ deref()

template<typename Element >
fcppt::optional::object< fcppt::reference< typename std::remove_reference< decltype( *std::declval< Element >) ) >::type >> fcppt::optional::deref ( fcppt::optional::object< Element > const &  _optional)
inline

Dereferences the contents of an optional.

If the optional is set to x, make_(c)ref(*x) is returned. For example, this is useful as a shortcut for optionals containing iterators or unique pointers.

◆ dynamic_cast_()

template<typename Result , typename Arg >
fcppt::optional::reference< Result> fcppt::optional::dynamic_cast_ ( fcppt::optional::reference< Arg > const &  _optional)

Converts an optional reference using dynamic_cast

Template Parameters
ResultA non reference type of the result
ArgA non reference type of the argument

Converts _optional using dynamic_cast to a Result & if _optional.has_value() is true. Otherwise, the empty optional will be returned.

Exceptions
std::bad_castif the conversion cannot be done

◆ filter()

template<typename Optional , typename Function >
std::decay< Optional>::type fcppt::optional::filter ( Optional &&  _source,
Function const &  _function 
)

Filters an optional.

If _source is set to x and _function(x) returns true, _source is returned. Otherwise, the empty optional is returned.

Template Parameters
FunctionA function callable as bool (Optional::value_type).

◆ from()

template<typename Optional , typename Default >
std::result_of< Default()>::type fcppt::optional::from ( Optional &&  _optional,
Default const  _default 
)

Returns the value contained in an optional or a default value.

If _optional is set to x, then x is returned. Otherwise, the result of _default is returned.

Template Parameters
DefaultMust be a function of type Optional::value_type ()

◆ from_pointer()

template<typename T >
fcppt::optional::reference< T> fcppt::optional::from_pointer ( T *const  _pointer)

Creates an optional reference from a pointer.

Creates an optional reference from _pointer. If _pointer is the null pointer, the result will be empty. Otherwise, the result will contain a reference to *_pointer.

◆ join()

template<typename Optional >
std::remove_cv< typename std::remove_reference< Optional >::type>::type::value_type fcppt::optional::join ( Optional &&  _source)
inline

Removes one layer of optionals.

Extracts the optional in _source or returns an empty optional.

Template Parameters
OptionalMust be an optional of optional

◆ make()

template<typename Type >
fcppt::optional::object< typename std::decay< Type >::type> fcppt::optional::make ( Type &&  _value)
inline

Wraps a value into an optional.

◆ make_if()

template<typename Function >
fcppt::optional::object< typename std::result_of< Function() >::type> fcppt::optional::make_if ( bool const  _is_set,
Function const &  _function 
)
inline

Creates an optional depending on a boolean.

If _is_set is true, then _function() is returned as an optional. Otherwise, the empty optional is returned.

Template Parameters
FunctionA function callable as R () where R is the result type.

◆ map()

template<typename Optional , typename Function >
auto fcppt::optional::map ( Optional &&  _source,
Function const &  _function 
) -> fcppt::optional::object< typename std::remove_cv< decltype( _function( fcppt::move_if_rvalue< Optional >( _source.get_unsafe() ) ) ) >::type >
inline

Maps over an optional using a function.

If _source is set to x, then optional(_function(x)) is returned. Otherwise, the empty optional is returned.

Template Parameters
FunctionA function callable as R (Optional::value_type) where R is the result type

◆ maybe()

template<typename Optional , typename Default , typename Transform >
std::result_of< Default()>::type fcppt::optional::maybe ( Optional &&  _optional,
Default const  _default,
Transform const  _transform 
)

Transforms an optional value or returns a default value.

For the lack of a better name, this function is called maybe like in Haskell. If _optional is set to x, then _transform(x) is returned. Otherwise, the result of _default is returned. This implies that _transform and _default must return the same type Ret. _optional can be perfectly forwarded into _transform, i.e. the optional's contents will be moved iff _optional is an rvalue.

Template Parameters
DefaultMust be a function of type Ret ()
TransformMust be a function of type Ret (Optional::value_type)

◆ maybe_multi()

template<typename Default , typename Transform , typename... Optionals>
std::result_of< Default()>::type fcppt::optional::maybe_multi ( Default const  _default,
Transform const  _transform,
Optionals &&...  _optionals 
)

Transforms multiple optional values or returns a default value.

A multi version of fcppt::optional::maybe. Unfortunately, the variadic template arguments must come last.

◆ maybe_void()

template<typename Optional , typename Transform >
void fcppt::optional::maybe_void ( Optional &&  _optional,
Transform const  _transform 
)
inline

Transforms an optional value or does nothing.

If _optional is set to x, then _transform(x) is called.

Template Parameters
TransformMust be a function of type void (Optional::value_type)

◆ maybe_void_multi()

template<typename... Optionals, typename Transform >
void fcppt::optional::maybe_void_multi ( Transform const  _transform,
Optionals &&...  _optionals 
)
inline

Transforms optional values or does nothing.

A multi version of fcppt::optional::maybe_void

◆ operator!=()

template<typename T >
bool fcppt::optional::operator!= ( fcppt::optional::object< T > const &  _a,
fcppt::optional::object< T > const &  _b 
)

Compares two optionals for inequality.

Compares _a and _b for inequality. Equal to !(_a == _b). This function requires T to be equality comparable.

Parameters
_aThe first optional
_bThe second optional

◆ operator<()

template<typename T >
bool fcppt::optional::operator< ( fcppt::optional::object< T > const &  _a,
fcppt::optional::object< T > const &  _b 
)

Compares two optionals lexicographically.

Compares _a and _b lexicographically. If one or both of them are empty, returns _a.has_value() < _b.has_value(), otherwise returns _a.get_unsafe() < _b.get_unsafe().

Parameters
_aThe first optional
_bThe second optional

◆ operator<<()

template<typename Type , typename Ch , typename Traits >
std::basic_ostream< Ch, Traits>& fcppt::optional::operator<< ( std::basic_ostream< Ch, Traits > &  _stream,
fcppt::optional::object< Type > const &  _opt_value 
)

Outputs an optional to a basic_ostream.

Outputs the value held by _opt_value to _stream, or nothing.

Parameters
_streamThe stream to output to
_opt_valueThe optional to output
Returns
_stream

◆ operator==()

template<typename T >
bool fcppt::optional::operator== ( fcppt::optional::object< T > const &  _a,
fcppt::optional::object< T > const &  _b 
)

Compares two optionals for equality.

Compares _a and _b for equality. Two optionals are equal if they are either both empty or if they are both not empty and their elements compare equal. This function requires T to be equality comparable.

Parameters
_aThe first optional
_bThe second optional

◆ static_cast_()

template<typename Result , typename Arg >
fcppt::optional::reference< Result> fcppt::optional::static_cast_ ( fcppt::optional::reference< Arg > const &  _optional)

Converts an optional reference using static_cast

Template Parameters
ResultA non reference type of the result
ArgA non reference type of the argument

Converts _optional using static_cast to a Result & if _optional.has_value() is true. Otherwise, the empty optional will be returned.

Warning
The behaviour is undefined if the static_cast is not well formed.

◆ to_container()

template<typename Container , typename Optional >
Container fcppt::optional::to_container ( Optional &&  _source)

Puts the value of an optional into a container or returns an empty container.

If _source holds x, then Container{x} is returned. Otherwise the empty container is returned.

Container and Optional must have the same value types.

Template Parameters
ContainerMust be constructible using fcppt::assign::make_container.

◆ to_exception()

template<typename Optional , typename MakeException >
auto fcppt::optional::to_exception ( Optional &&  _optional,
MakeException const  _make_exception 
) -> decltype( fcppt::move_if_rvalue< Optional >( _optional.get_unsafe() ) )
inline

Returns the value contained in an optional or throws an exception.

If _optional is set to x, then x is returned. Otherwise, the result of _make_exception is thrown as an exception.

Template Parameters
MakeExceptionMust be a nullary function returning an object type

◆ to_pointer()

template<typename T >
T* fcppt::optional::to_pointer ( fcppt::optional::reference< T > const  _optional)
inline

Converts an optional reference to a pointer.

If _optional is empty, returns nullptr. Otherwise, returns the address of the referenced object of _optional.