### TypedInPlaceFactory Implementation Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/in_place_factories.html Example implementation of a TypedInPlaceFactory class that encapsulates constructor parameters for a specific type. ```cpp template class TypedInPlaceFactory2 { A0 m_a0 ; A1 m_a1 ; public: TypedInPlaceFactory2( A0 const& a0, A1 const& a1 ) : m_a0(a0), m_a1(a1) {} void construct ( void* p ) { new (p) T(m_a0,m_a1) ; } } ; ``` -------------------------------- ### Indeterminate Value Example Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/optional/design.html Demonstrates the creation of an automatic object with an indeterminate value, which leads to undefined or erroneous behavior if read before assignment. ```cpp { int i; // indeterminate value populate(&i); cout << i; } ``` -------------------------------- ### Member Functions for optional Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___optional_references.html Details on member functions like emplace, get, operator*, and operator->. ```APIDOC ## Member Functions for optional ### `emplace` ```cpp void optional::emplace( R&& r ) noexcept ; ``` * **Effects:** Assigns `ref` with expression `r`. * **Postconditions:** `bool(*this) == true`. * **Remarks:** Unless `R` is an lvalue reference, the program is ill-formed. This function does not participate in overload resolution if `decay` is an instance of `boost::optional`. ### Dereference Operators (`get`, `operator*`) ```cpp T& optional::get() const ; T& optional::operator *() const ; ``` * **Requires:** `bool(*this) == true`. * **Effects:** Returns `*ref`. * **Throws:** Nothing. * **Example:** ```cpp T v; T& vref = v; optional opt ( vref ); T const& vref2 = *opt; assert ( vref2 == v ); ++ v; assert ( *opt == v ); ``` ### Arrow Operator (`operator->`) ```cpp T* optional::operator -> () const ; ``` * **Requires:** `bool(*this) == true`. * **Effects:** Returns `ref`. * **Throws:** Nothing. ### `value` ```cpp T& optional::value() const ; ``` ``` -------------------------------- ### std::optional Static Assertion Example Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/convenience_conversions_and_deductions.html Uses a static assertion to check the equality comparability between std::optional and a non-optional type, highlighting potential concept-related issues. ```cpp static_assert(std::equality_comparable_with, Threshold>); ``` -------------------------------- ### Assigning to Uninitialized Optional Reference Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/optional_references/rebinding_semantics_for_assignment_of_optional_references.html When assigning to an uninitialized `optional`, it binds to the object for the first time. This example shows the initial binding and subsequent modification of the referenced object. ```cpp int x = 1 ; int& rx = x ; optional ora ; optional orb(x) ; ora = orb ; // now 'ora' is bound to 'x' through 'rx' *ora = 2 ; // Changes value of 'x' through 'ora' assert(x==2); ``` -------------------------------- ### Using boost::optional for Configuration Parameters Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/index.html Demonstrates how to handle optional configuration values that may or may not be present, avoiding the need for sentinel values. ```cpp #include boost::optional getConfigParam(std::string name); // return either an int or a `not-an-int` int main() { if (boost::optional oi = getConfigParam("MaxValue")) // did I get a real int? runWithMax(*oi); // use my int else runWithNoMax(); } ``` -------------------------------- ### No-Value Initialization: Boost vs. Std Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/std_comp.html Demonstrates the different ways to initialize an optional with no value in Boost.Optional and std::optional. ```cpp optional o = none; ``` ```cpp optional o = nullopt; ``` -------------------------------- ### Using IO operators with boost::optional Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/io_operators.html Demonstrates basic input and output operations for optional types. Requires including the boost/optional/optional_io.hpp header. ```cpp #include #include int main() { boost::optional o1 = 1, oN = boost::none; std::cout << o1; std::cin >> oN; } ``` -------------------------------- ### Get pointer to optional value Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___free_functions.html Returns a pointer to the contained value of an optional. Throws no exceptions. ```cpp auto get_pointer ( optional& o ) -> typename optional::pointer_type ; auto get_pointer ( optional const& o ) -> typename optional::pointer_const_type ; ``` -------------------------------- ### Get optional value or default Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___free_functions.html Returns the contained value of an optional or a default value if the optional is uninitialized. This function is deprecated. ```cpp auto get_optional_value_or ( optional& o, typename optional::reference_type def ) -> typename optional::reference_type ; auto get_optional_value_or ( optional const& o, typename optional::reference_const_type def ) -> typename optional::reference_const_type ; ``` -------------------------------- ### Initialize and Assign Optional Objects Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/iface.html Demonstrates how to construct and assign values to optional objects, including the use of the none tag. ```cpp optional o1; // contains no value optional o2 = 2; // contains value 2 optional o3 = none; // contains no value o1 = 1; // assign value 1 o2 = none; // assign a no-value o3 = {}; // assign a no-value ``` -------------------------------- ### Boost.Optional Explicit Operations Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/convenience_conversions_and_deductions.html Demonstrates the explicit and verbose syntax recommended by Boost.Optional for operations like creating an optional or comparing values, ensuring clarity and preventing silent bugs. ```cpp Threshold th; auto o = boost::make_potional(th); // *always* add a new layer of optionality return boost::equal_pointees(o, th); // *always* unpack optionals for comparison return o && *o == th; // *always* treat the right-hand side argument as value ``` -------------------------------- ### Getting optional value or a fallback (deprecated) Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___optional_references.html Retrieves the contained reference or a fallback value if the optional is empty. This function is deprecated and is equivalent to `value_or`. ```cpp template T& optional::get_value_or( R&& r ) const noexcept; ``` -------------------------------- ### Standard Wrapper Construction Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/in_place_factories.html Demonstrates the standard approach of initializing a wrapped object via a copy constructor, which requires a temporary object. ```cpp struct X { X ( int, std::string ) ; } ; class W { X wrapped_ ; public: W ( X const& x ) : wrapped_(x) {} } ; void foo() { // Temporary object created. W ( X(123,"hello") ) ; } ``` -------------------------------- ### In-Place Initialization: Boost vs. Std Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/std_comp.html Compares the syntax for in-place initialization of optional types with constructor arguments. ```cpp optional o {in_place_init, a, b}; ``` ```cpp optional o {in_place, a, b}; ``` -------------------------------- ### Accessing optional value with a function fallback Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___optional_references.html Use this to get the contained reference or the result of a function call if the optional is empty. The function is called only if the optional is empty. ```cpp template T& optional::value_or( F f ) const ; ``` -------------------------------- ### Initialize and Assign optional with std::move Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___optional_values.html Demonstrates initialization and assignment using `std::move` for `boost::optional`. Ensure `T` is `MoveConstructible` and `MoveAssignable`. ```cpp T x; optional def ; optional opt(x) ; T y1, y2, yR; def = std::move(y1) ; assert ( *def == yR ) ; opt = std::move(y2) ; assert ( *opt == yR ) ; ``` -------------------------------- ### Basic Optional Initialization Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___optional_values.html Initializes an optional object and verifies its state. ```cpp optional y(x) ; assert( *y == 123 ) ; ``` -------------------------------- ### Getting a pointer to the contained reference Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___optional_references.html Returns a pointer to the contained reference if the optional has a value, otherwise returns nullptr. This is a safe way to access the reference without exceptions. ```cpp T* optional::get_ptr () const noexcept; ``` -------------------------------- ### Optional References: Boost vs. Std Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/std_comp.html Demonstrates that Boost.Optional supports optional references, a feature not available in std::optional. ```cpp optional o; ``` -------------------------------- ### Generic In-Place Factory Usage Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/in_place_factories.html Shows how a wrapper can use a generic InPlaceFactory to construct an object in-place. ```cpp class W { X wrapped_ ; public: W ( X const& x ) : wrapped_(x) {} template< class InPlaceFactory > W ( InPlaceFactory const& fac ) { fac.template construct(&wrapped_) ; } } ; void foo() { // Wrapped object constructed in-place via a InPlaceFactory. // No temporary created. W ( in_place(123,"hello") ) ; } ``` -------------------------------- ### Accessing optional value or returning a fallback Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___optional_references.html Use this to get the contained reference or a provided fallback value if the optional is empty. The fallback value is returned by copy or move. ```cpp template T& optional::value_or( R&& r ) const noexcept; ``` -------------------------------- ### Safely Extract Value with Assertion Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/quick_overview.html When you are certain a string converts to a valid integer, you can directly dereference the result of convert. This example uses BOOST_ASSERT to guard against potential undefined behavior. ```cpp int i = *convert("100"); ``` -------------------------------- ### In-Place Initialization with Initializer List: Boost vs. Std Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/std_comp.html Highlights that std::optional supports in-place initialization with an initializer list, while Boost.Optional does not. ```cpp optional> o {in_place, {1, 2, 3}}; o.emplace({4, 5, 6}); ``` -------------------------------- ### Basic optional Usage Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/type_requirements.html Demonstrates the basic initialization and checking of an uninitialized optional object. Accessing the value of an uninitialized optional will always throw. ```cpp optional o; // uninitialized assert(o == none); // check if initialized assert(!o); // o.value(); // always throws ``` -------------------------------- ### Extract Optional Value or Evaluate Callback Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/quick_overview.html Use .value_or_eval(callback) to get the contained value or execute a provided callback function if the optional is uninitialized. The callback's return value is then used. ```cpp int fallback_to_default() { cerr << "could not convert; using -1 instead" << endl; return -1; } int l = convert(text).value_or_eval(fallback_to_default); ``` -------------------------------- ### Wrapper Using TypedInPlaceFactory Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/in_place_factories.html Demonstrates a wrapper class designed to accept a TypedInPlaceFactory to construct its internal object. ```cpp class W { X wrapped_ ; public: W ( X const& x ) : wrapped_(x) {} W ( TypedInPlaceFactory2 const& fac ) { fac.construct(&wrapped_) ; } } ; void foo() { // Wrapped object constructed in-place via a TypedInPlaceFactory. // No temporary created. W ( TypedInPlaceFactory2(123,"hello")) ; } ``` -------------------------------- ### Rebinding Initialized Optional Reference Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/optional_references/rebinding_semantics_for_assignment_of_optional_references.html Assigning to an initialized `optional` rebinds it to the new object, unlike bare C++ references. This example shows how `ora` is rebound to `b` and subsequent modifications affect `b`. ```cpp int a = 1 ; int b = 2 ; int& ra = a ; int& rb = b ; optional ora(ra) ; optional orb(rb) ; ora = orb ; // 'ora' is rebound to 'b' *ora = 3 ; // Changes value of 'b' (not 'a') assert(a==1); assert(b==3); ``` -------------------------------- ### Assigning to Bare C++ Reference Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/optional_references/rebinding_semantics_for_assignment_of_optional_references.html Assigning to a bare C++ reference forwards the assignment to the referenced object, changing its value but not rebinding the reference itself. This example demonstrates that the reference remains bound to the original object. ```cpp int a = 1 ; int& ra = a ; int b = 2 ; int& rb = b ; ra = rb ; // Changes the value of 'a' to 'b' assert(a==b); b = 3 ; assert(ra!=b); // 'ra' is not rebound to 'b' ``` -------------------------------- ### Move-Constructing an Optional Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___optional_values.html Demonstrates move-constructing an optional from another optional. ```cpp optional x(123.4); assert ( *x == 123.4 ) ; optional y(std::move(x)) ; assert( *y == 123 ) ; ``` -------------------------------- ### Compare optional objects Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/relational_operators.html Demonstrates equality comparisons between optional objects and the uninitialized state. ```cpp boost::optional oN = boost::none; boost::optional o0 = 0; boost::optional o1 = 1; assert(oN != o0); assert(o1 != oN); assert(o0 != o1); assert(oN == oN); assert(o0 == o0); ``` -------------------------------- ### Optional Specialization for Lvalue References Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/header_optional_optional_refs.html This code defines the `optional` class template, a specialization for handling lvalue references. It includes constructors, assignment operators, and member functions like `get()`, `operator*()`, `operator->()`, `value()`, `value_or()`, `map()`, `flat_map()`, `get_ptr()`, `has_value()`, `operator bool()`, `operator!()`, and `reset()`. Deprecated methods are also listed. ```cpp template class optional // specialization for lvalue references { public : typedef T& value_type; typedef T& reference_type; typedef T& reference_const_type; // no const propagation typedef T& rval_reference_type; typedef T* pointer_type; typedef T* pointer_const_type; // no const propagation optional () noexcept ; optional ( none_t ) noexcept ; template optional(R&& r) noexcept ; template optional(bool cond, R&& r) noexcept ; optional ( optional const& rhs ) noexcept ; template explicit optional ( optional const& rhs ) noexcept ; optional& operator = ( none_t ) noexcept ; optional& operator = ( optional const& rhs ) noexcept; template optional& operator = ( optional const& rhs ) noexcept ; template optional& operator = (R&& r) noexcept ; template void emplace ( R&& r ) noexcept ; T& get() const ; T& operator *() const ; T* operator ->() const ; T& value() const& ; template T& value_or( R && r ) const noexcept ; template T& value_or_eval( F f ) const ; template auto map( F f ) const -> _see below_; template auto flat_map( F f ) const -> _see below_; T* get_ptr() const noexcept ; bool has_value() const noexcept ; explicit operator bool() const noexcept ; bool operator!() const noexcept ; void reset() noexcept ; // deprecated methods // (deprecated) template void reset ( R && r ) noexcept ; // (deprecated) bool is_initialized() const noexcept ; // (deprecated) template T& get_value_or( R && r ) constnoexcept; private: T* ref; // exposition only }; ``` -------------------------------- ### std::optional Convenience Conversions Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/convenience_conversions_and_deductions.html Demonstrates implicit conversions and comparisons that std::optional supports, which can sometimes lead to unexpected behavior. ```cpp std::optional oi = 1; // OK std:string_view sv = "hi"; std::optional os = sv; // OK os == sv; // OK std::optional osv; std::optional os2 = osv; // OK os2 == osv; // OK ``` -------------------------------- ### Compare optional with values Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/relational_operators.html Demonstrates mixed comparisons between optional objects and raw values or boost::none. ```cpp assert(oN != 0); assert(o1 != boost::none); assert(o0 != 1); assert(oN == boost::none); assert(o0 == 0); ``` -------------------------------- ### Using the negation operator for optional Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___optional_values.html Demonstrates checking the initialization state of an optional object using the negation operator and the double-bang idiom. ```cpp optional opt ; assert ( !opt ); *opt = some_T ; // Notice the "double-bang" idiom here. assert ( !!opt ) ; ``` -------------------------------- ### Forward declarations for boost::optional Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_fwd_hpp_.html Contains the namespace declarations for the optional class template and swap utility. ```cpp namespace boost { template class optional ; template void swap ( optional& , optional& ); template struct optional_swap_should_use_default_constructor ; } // namespace boost ``` -------------------------------- ### Lazy Load Optimization with Boost.Optional Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/quick_overview/optional_data_members.html Demonstrates lazy initialization of a `Resource` member using `boost::optional`. The `emplace` function is used to initialize the optional in-place, avoiding copy or move constructions. This is useful when resource initialization is expensive and may not always be required. ```cpp class Widget { mutable boost::optional resource_; public: Widget() {} const Resource& getResource() const // not thread-safe { if (resource_ == boost::none) resource_.emplace("resource", "arguments"); return *resource_; } }; ``` -------------------------------- ### Initialize and Check Optional in One Step Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/quick_overview.html Combine the initialization of a boost::optional object and the check for its value into a single 'if' statement for concise code. ```cpp if (boost::optional oi = convert(text)) int i = *oi; ``` -------------------------------- ### Printing to IOStreams: Boost vs. Std Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/std_comp.html Demonstrates that Boost.Optional supports direct printing to IOStreams, a capability not present in std::optional. ```cpp std::cout << optional{}; ``` -------------------------------- ### Handling optional user input Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/optional/advice.html Demonstrates using optional to handle user input where an empty string might signify missing text, allowing for a dedicated program path. This pattern requires translating empty strings to a state with no contained value within the function returning the optional. ```cpp if(boost::optional name = ask_user_name()) { assert(*name != ""); logon_as(*name); } else { skip_logon(); } ``` -------------------------------- ### Boost Optional Usage with GCC -Wmaybe-uninitialized Warning Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/gotchas/false_positive_with__wmaybe_uninitialized.html This code demonstrates a scenario where GCC compilers below version 5.1 might issue an -Wmaybe-uninitialized warning with boost::optional, even with valid usage. It's recommended to use the workaround provided in the documentation if this warning appears. ```cpp #include boost::optional getitem(); int main(int argc, const char *[]) { boost::optional a = getitem(); boost::optional b; if (argc > 0) b = argc; if (a != b) return 1; return 0; } ``` -------------------------------- ### Implement convert function with boost::optional Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/quick_overview/optional_automatic_variables.html Demonstrates a function that returns an optional integer, ensuring a single return statement and well-defined state. ```cpp boost::optional convert(const std::string& text) { boost::optional ans; std::stringstream s(text); int i; if ((s >> i) && s.get() == std::char_traits::eof()) ans = i; return ans; } ``` -------------------------------- ### Portable Optional Reference Initialization Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/dependencies_and_portability/optional_reference_binding.html Use direct-initialization and explicit construction to ensure portability across compilers that handle reference binding differently. ```cpp const int i = 0; optional or1; optional or2 = i; // caution: not portable or1 = i; // caution: not portable optional or3(i); // portable or1 = optional(i); // portable ``` -------------------------------- ### Conditional Initialization from T: Boost vs. Std Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/std_comp.html Illustrates that Boost.Optional supports conditional initialization from a value of type T, a feature absent in std::optional. ```cpp optional o {cond, x}; ``` -------------------------------- ### Constructors for optional Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___optional_references.html Details on how to construct optional references. ```APIDOC ## Constructors for optional ### Default Constructor ```cpp optional::optional() noexcept; optional::optional(none_t) noexcept; ``` * **Postconditions:** `bool(*this) == false`; `*this` refers to nothing. ### Initializing with a Reference ```cpp template optional::optional(R&& r) noexcept; ``` * **Postconditions:** `bool(*this) == true`; `addressof(**this) == addressof(r)`. * **Remarks:** Unless `R` is an lvalue reference, the program is ill-formed. This constructor does not participate in overload resolution if `decay` is an instance of `boost::optional`. * **Notes:** This constructor is declared `explicit` on compilers that do not correctly support binding to const lvalues of integral types. * **Example:** ```cpp T v; T& vref = v; optional opt(vref); assert ( *opt == v ); ++ v; // mutate referee assert (*opt == v); ``` ### Initializing with a Conditional Reference ```cpp template optional::optional(bool cond, R&& r) noexcept; ``` * **Effects:** Initializes `ref` with expression `cond ? addressof(r) : nullptr`. * **Postconditions:** `bool(*this) == cond`; If `bool(*this)`, `addressof(**this) == addressof(r)`. * **Remarks:** Unless `R` is an lvalue reference, the program is ill-formed. This constructor does not participate in overload resolution if `decay` is an instance of `boost::optional`. ### Copy Constructor ```cpp optional::optional ( optional const& rhs ) noexcept ; ``` * **Effects:** Initializes `ref` with expression `rhs.ref`. * **Postconditions:** `bool(*this) == bool(rhs)`. * **Example:** ```cpp optional uninit; assert (!uninit); optional uinit2 ( uninit ); assert ( uinit2 == uninit ); T v = 2; T& ref = v; optional init(ref); assert ( *init == v ); optional init2 ( init ); assert ( *init2 == v ); v = 3; assert ( *init == 3 ); assert ( *init2 == 3 ); ``` ### Converting Copy Constructor ```cpp template explicit optional::optional ( optional const& rhs ) noexcept ; ``` * **Requires:** `is_convertible::value` is `true`. * **Effects:** Initializes `ref` with expression `rhs.ref`. * **Postconditions:** `bool(*this) == bool(rhs)`. ``` -------------------------------- ### Initializing optional with emplace() Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/type_requirements.html Shows how to initialize an optional object using the `emplace()` function when the contained type `T` has an accessible constructor. This is an alternative to In-Place Factories if compiler support is limited. ```cpp optional o; o.emplace("T", "ctor", "params"); ``` -------------------------------- ### Conditional In-Place Initialization: Boost vs. Std Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/std_comp.html Shows that Boost.Optional has a syntax for conditional in-place initialization, which is not present in std::optional. ```cpp optional o {in_place_init_if, cond, a, b}; ``` -------------------------------- ### Comparison Behaviors of optional Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/gotchas.html Illustrates how mixed comparisons between optional and bool values can produce unexpected results compared to standard boolean logic. ```cpp optional oEmpty(none), oTrue(true), oFalse(false); if (oEmpty == none); // renders true if (oEmpty == false); // renders false! if (oEmpty == true); // renders false if (oFalse == none); // renders false if (oFalse == false); // renders true! if (oFalse == true); // renders false if (oTrue == none); // renders false if (oTrue == false); // renders false if (oTrue == true); // renders true ``` -------------------------------- ### Constructors from U and optional: Boost vs. Std Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/std_comp.html Compares the explicitness of constructors for optional types when initializing from another type U or an optional of U. ```cpp optional o {U{}}; optional o {optional{}}; ``` ```cpp optional o = U{}; optional o = optional{} ``` -------------------------------- ### Boost.Optional Header Synopsis Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/optional/reference/header__boost_optional_optional_hpp_.html This snippet provides a synopsis of the header, outlining the classes, functions, and operators available for use with Boost.Optional. ```APIDOC ## Header ### Description This header provides the `boost::optional` class template and related functionalities for handling values that may or may not be present. ### Synopsis ```cpp // In Header: namespace boost { class in_place_init_t { /* see below */ } ; inline constexpr in_place_init_t in_place_init ( /* see below */ ) ; class in_place_init_if_t { /*see below*/ } ; inline constexpr in_place_init_if_t in_place_init_if ( /*see below*/ ) ; template class optional ; template class optional ; template inline bool operator == ( optional const& x, optional const& y ) ; template inline bool operator != ( optional const& x, optional const& y ) ; template inline bool operator < ( optional const& x, optional const& y ) ; template inline bool operator > ( optional const& x, optional const& y ) ; template inline bool operator <= ( optional const& x, optional const& y ) ; template inline bool operator >= ( optional const& x, optional const& y ) ; template inline bool operator == ( optional const& x, none_t ) noexcept ; template inline bool operator != ( optional const& x, none_t ) noexcept ; template inline optional make_optional ( T const& v ) ; template inline optional> make_optional ( T && v ) ; template inline optional make_optional ( bool condition, T const& v ) ; template inline optional> make_optional ( bool condition, T && v ) ; template inline auto get_optional_value_or ( optional const& opt, typename optional::reference_const_type def ) -> typename optional::reference_const_type; template inline auto get_optional_value_or ( optional const& opt, typename optional::reference_type def ) -> typename optional::reference_type ; template inline T const& get ( optional const& opt ) ; template inline T& get ( optional & opt ) ; template inline T const* get ( optional const* opt ) ; template inline T* get ( optional* opt ) ; template inline auto get_pointer ( optional const& opt ) -> _see below_; template inline auto get_pointer ( optional & opt ) -> _see below_; template inline void swap( optional& x, optional& y ) ; template inline void swap( optional& x, optional& y ) ; } // namespace boost namespace std { template struct hash > ; template struct hash > ; } // namespace std ``` ### Classes - `boost::optional`: Represents an optional value of type `T`. - `boost::optional`: Represents an optional reference to a value of type `T`. - `boost::in_place_init_t`: Tag type for in-place construction. - `boost::in_place_init_if_t`: Tag type for conditional in-place construction. ### Functions - `boost::make_optional`: Factory function to create `optional` objects. - `boost::get_optional_value_or`: Retrieves the value of an `optional` or a default value. - `boost::get`: Accesses the contained value of an `optional`. - `boost::get_pointer`: Returns a pointer to the contained value. - `boost::swap`: Swaps the contents of two `optional` objects. ### Operators - Comparison operators (`==`, `!=`, `<`, `>`, `<=`, `>=`) for comparing `optional` objects with each other and with `none_t`. ### Namespace - `boost` - `std` (for `std::hash` specialization) ``` -------------------------------- ### In-Place Initialization Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___optional_values.html Constructs objects directly within the optional using in-place initialization. ```cpp // creates an std::mutex using its default constructor optional om {in_place_init}; assert (om); // creates a unique_lock by calling unique_lock(*om, std::defer_lock) optional> ol {in_place_init, *om, std::defer_lock}; assert (ol); assert (!ol->owns_lock()); ``` -------------------------------- ### Boost Optional Header Reference Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/optional/reference.html Documentation for the header, which defines the tag used to represent an empty state in optional objects. ```APIDOC ## Header ### Description Defines the `none_t` tag and `none` constant used to indicate that an optional object does not contain a value. ### Components - **none_t** (class) - An empty, trivially copyable class with a disabled default constructor, used as a tag for selecting overloads in the `optional` interface. - **none** (constant) - An inline constexpr instance of `none_t` used to indicate an optional object that does not contain a value during initialization, assignment, or relational operations. ``` -------------------------------- ### Initialization Tags Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/header_optional_in_place_init.html Defines the `in_place_init_t` and `in_place_init_if_t` types and constants used for controlling overload resolution in the initialization of optional objects. ```APIDOC ## Initialization Tags ### Description Classes `in_place_init_t` and `in_place_init_if_t` are empty classes designed to influence overload resolution during the initialization of optional objects. They are trivially copyable and have a disabled default constructor. ### Namespace `boost` ### Types - `in_place_init_t`: An empty class used as a tag for in-place initialization. - `in_place_init_if_t`: An empty class used as a tag for conditional in-place initialization. ### Constants - `in_place_init`: An instance of `in_place_init_t`. - `in_place_init_if`: An instance of `in_place_init_if_t`. ### Usage Example (Conceptual) ```cpp #include // Assuming boost::optional is configured to use these tags boost::optional opt1(boost::in_place_init, arg1, arg2); boost::optional opt2(boost::in_place_init_if, arg1, arg2); ``` ### Copyright and License Copyright © 2003-2007 Fernando Luis Cacciola Carballal Copyright © 2014-2024 Andrzej Krzemieński Distributed under the Boost Software License, Version 1.0. ``` -------------------------------- ### Boost.Optional Header Synopsis Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/optional/reference/header__boost_optional_optional_hpp_.html Contains the declarations for the optional class template, factory functions, and standard library hash specializations. ```cpp // In Header: namespace boost { class in_place_init_t { /* see below */ } ; inline constexpr in_place_init_t in_place_init ( /* see below */ ) ; class in_place_init_if_t { /*see below*/ } ; inline constexpr in_place_init_if_t in_place_init_if ( /*see below*/ ) ; template class optional ; template class optional ; template inline bool operator == ( optional const& x, optional const& y ) ; template inline bool operator != ( optional const& x, optional const& y ) ; template inline bool operator < ( optional const& x, optional const& y ) ; template inline bool operator > ( optional const& x, optional const& y ) ; template inline bool operator <= ( optional const& x, optional const& y ) ; template inline bool operator >= ( optional const& x, optional const& y ) ; template inline bool operator == ( optional const& x, none_t ) noexcept ; template inline bool operator != ( optional const& x, none_t ) noexcept ; template inline optional make_optional ( T const& v ) ; template inline optional> make_optional ( T && v ) ; template inline optional make_optional ( bool condition, T const& v ) ; template inline optional> make_optional ( bool condition, T && v ) ; template inline auto get_optional_value_or ( optional const& opt, typename optional::reference_const_type def ) -> typename optional::reference_const_type; template inline auto get_optional_value_or ( optional const& opt, typename optional::reference_type def ) -> typename optional::reference_type ; template inline T const& get ( optional const& opt ) ; template inline T& get ( optional & opt ) ; template inline T const* get ( optional const* opt ) ; template inline T* get ( optional* opt ) ; template inline auto get_pointer ( optional const& opt ) -> _see below_; template inline auto get_pointer ( optional & opt ) -> _see below_; template inline void swap( optional& x, optional& y ) ; template inline void swap( optional& x, optional& y ) ; } // namespace boost namespace std { template struct hash > ; template struct hash > ; } // namespace std ``` -------------------------------- ### Inspect Optional Object State Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/iface.html Shows how to check for the presence of a value and access it using pointer-like syntax. ```cpp void inspect (optional os) { if (os) { // contextual conversion to `bool` read_string(*os); // `operator*` to access the stored value read_int(os->size()); // `operator->` as shortcut for accessing members } } ``` -------------------------------- ### In-place construction with emplace Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___optional_values.html Demonstrates creating or replacing the contained value in-place using various constructor arguments. ```cpp T v; optional opt; opt.emplace(0); // create in-place using ctor T(int) opt.emplace(); // destroy previous and default-construct another T opt.emplace(v); // destroy and copy-construct in-place (no assignment called) ``` -------------------------------- ### Store boost::optional in std::map Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/quick_overview/storage_in_containers.html Demonstrates using boost::optional as a key in a map to track frequencies, including uninitialized states. ```cpp std::map, int> choices; for (int i = 0; i < LIMIT; ++i) { boost::optional choice = readChoice(); ++choices[choice]; } ``` -------------------------------- ### make_optional with Condition: Boost vs. Std Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/std_comp.html Illustrates that Boost.Optional has a `make_optional` function that accepts a condition, a feature not in std::optional. ```cpp make_optional(cond, v); ``` -------------------------------- ### std::optional Initialization Ambiguity Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/convenience_conversions_and_deductions.html Illustrates how std::optional's constructors can lead to ambiguity, especially when dealing with nested optionals or type aliases. ```cpp Threshold th = /*வுகளை*/; std::optional o = th; assert (o); ``` ```cpp using Threshold = std::optional; Threshold th; std::optional o = th; assert(o); ``` ```cpp template optional(U const&); template optional(optional const&); ``` -------------------------------- ### Synopsis for boost/optional/optional_io.hpp Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/io_header.html Provides the declarations for stream insertion and extraction operators for optional types. ```cpp #include #include #include namespace boost { template std::basic_ostream& operator<<(std::basic_ostream& out, optional const& v); template std::basic_ostream& operator<<(std::basic_ostream& out, none_t const&); template std::basic_istream& operator>>(std::basic_istream& in, optional& v); } // namespace boost ``` -------------------------------- ### Synopsis of boost/none.hpp Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/optional/reference.html Defines the none_t tag class and the none constant for use with optional objects. ```cpp namespace boost { class none_t {/* see below */}; inline constexpr none_t none (/* see below */); } // namespace boost ``` -------------------------------- ### Workaround for GCC -Wmaybe-uninitialized Warning with Boost Optional Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/gotchas/false_positive_with__wmaybe_uninitialized.html This is a workaround for the -Wmaybe-uninitialized warning that can occur with boost::optional on certain GCC versions. It initializes an optional containing no value in a way that suppresses the compiler warning. ```cpp boost::optional b = boost::make_optional(false, int()); ``` -------------------------------- ### Optimized record structure layout Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/advice/performance_considerations.html A reordered structure layout to minimize padding and total size. ```cpp struct Record { bool _has_min; bool _has_max; int _min; int _max; }; ``` -------------------------------- ### Swap optional objects Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___free_functions.html Demonstrates swapping two optional objects, including cases where one or both are uninitialized. ```cpp T x(12); T y(21); optional def0 ; optional def1 ; optional optX(x); optional optY(y); boost::swap(def0,def1); // no-op boost::swap(def0,optX); assert ( *def0 == x ); assert ( !optX ); boost::swap(def0,optX); // Get back to original values boost::swap(optX,optY); assert ( *optX == y ); assert ( *optY == x ); ``` -------------------------------- ### Construct bad_optional_access Exception Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_bad_optional_access_hpp_/detailed_semantics.html Constructs an object of class bad_optional_access. The what() method returns an implementation-defined NTBS. ```cpp bad_optional_access(); ``` -------------------------------- ### Comparisons with U and optional: Std vs. Boost Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/std_comp.html Shows that std::optional supports comparisons with other types and optional types, unlike Boost.Optional. ```cpp optional{} == U{}; optional{} == optional{} ``` -------------------------------- ### bad_optional_access Exception Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_bad_optional_access_hpp_/detailed_semantics.html Details about the `bad_optional_access` exception class used in Boost.Optional. ```APIDOC ## `bad_optional_access()` ### Description Constructs an object of class `bad_optional_access`. ### Method Constructor ### Endpoint N/A ### Parameters None ### Request Example N/A ### Response #### Success Response (N/A) N/A #### Response Example N/A ### Postconditions `what()` returns an implementation-defined NTBS (Null-Terminated Byte String). ``` -------------------------------- ### Optional Reference Initialization Restrictions Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/design/optional_references.html Demonstrates that optional references cannot be initialized from temporaries, unlike standard C++ references. ```cpp const int& i = 1; // legal optional oi = 1; // illegal ``` -------------------------------- ### Construct Optional from boost::none Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___optional_values.html Construct an optional using boost::none to explicitly create an uninitialized optional. T's default constructor is not called. ```cpp #include optional n(none) ; assert ( !n ) ; ``` -------------------------------- ### optional Constructors Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___optional_values.html API documentation for the various ways to construct an optional object. ```APIDOC ## optional::optional() ### Description Default-Constructs an optional. The object is left uninitialized and T's default constructor is not called. ### Method Constructor ### Request Example optional def; assert(!def); ``` ```APIDOC ## optional::optional(none_t) ### Description Constructs an optional in an uninitialized state using the none_t tag. ### Method Constructor ### Request Example #include optional n(none); assert(!n); ``` ```APIDOC ## optional::optional(T const& v) ### Description Directly-Constructs an optional by copying the provided value v. ### Method Constructor ### Parameters #### Request Body - **v** (T const&) - Required - The value to copy into the optional. ### Request Example T v; optional opt(v); assert(*opt == v); ``` ```APIDOC ## optional::optional(T&& v) ### Description Directly-Move-Constructs an optional from the provided value v. ### Method Constructor ### Parameters #### Request Body - **v** (T&&) - Required - The value to move into the optional. ### Request Example T v1; optional opt(std::move(v1)); ``` ```APIDOC ## optional::optional(optional const& rhs) ### Description Copy-Constructs an optional from another optional instance. ### Method Constructor ### Parameters #### Request Body - **rhs** (optional const&) - Required - The optional instance to copy from. ### Request Example optional init(T(2)); optional init2(init); assert(init2 == init); ``` ```APIDOC ## optional::optional(optional&& rhs) ### Description Move-constructs an optional from another optional instance. ### Method Constructor ### Parameters #### Request Body - **rhs** (optional&&) - Required - The optional instance to move from. ### Request Example optional> init(std::unique_ptr(new T(2))); optional> init2(std::move(init)); ``` ```APIDOC ## template optional::optional(optional const& rhs) ### Description Copy-Constructs an optional by converting the value from an optional of a different type U. ### Method Constructor ### Parameters #### Request Body - **rhs** (optional const&) - Required - The optional instance of type U to convert from. ### Request Example optional x(123.4); assert(*x == 123.4); ``` -------------------------------- ### make_optional Functions Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/detailed_semantics___free_functions.html Functions to create optional objects with different initialization strategies. ```APIDOC ## make_optional Functions ### Description Functions to create `optional` objects. ### `optional make_optional( T const& v )` * **Returns:** `optional(v)` for the deduced type `T` of `v`. * **Example:** ```cpp template void foo ( optional const& opt ) ; foo ( make_optional(1+1) ) ; // Creates an optional ``` ### `optional> make_optional( T && v )` * **Returns:** `optional>(std::move(v))` for the deduced type `T` of `v`. ### `optional make_optional( bool condition, T const& v )` * **Returns:** `optional(condition, v)` for the deduced type `T` of `v`. * **Example:** ```cpp optional calculate_foo() { double val = compute_foo(); return make_optional(is_not_nan_and_finite(val),val); } optional v = calculate_foo(); if ( !v ) error("foo wasn't computed"); ``` ### `optional> make_optional( bool condition, T && v )` * **Returns:** `optional>(condition, std::move(v))` for the deduced type `T` of `v`. ``` -------------------------------- ### Template Parameter Deduction: Boost vs. Std Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/std_comp.html Shows that std::optional allows for template parameter deduction during initialization, unlike Boost.Optional. ```cpp optional o = 1; ``` -------------------------------- ### Define Initialization Tags in Boost Source: https://www.boost.org/doc/libs/latest/libs/optional/doc/html/boost_optional/reference/header__boost_optional_optional_hpp_/header_optional_in_place_init.html Defines the empty classes `in_place_init_t` and `in_place_init_if_t` and their corresponding constants. These are used to control overload resolution during the initialization of optional objects. ```cpp namespace boost { class in_place_init_t { /* see below */ } ; const in_place_init_t in_place_init ( /* see below */ ) ; class in_place_init_if_t { /*see below*/ } ; const in_place_init_if_t in_place_init_if ( /*see below*/ ) ; } ```