Namespaces
Variants

std::make_optional

From cppreference.com
 
 
Utilities library
General utilities
Relational operators (deprecated in C++20)
Integer comparison functions
(C++20)(C++20)(C++20)    
(C++20)
Swap and type operations
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
Undefined behavior utilities
Common vocabulary types
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
 
 
Defined in header <optional>
template< class T >
constexpr std::optional<std::decay_t<T>> make_optional( T&& value );
(1) (since C++17)
template< class T, class... Args >
constexpr std::optional<T> make_optional( Args&&... args );
(2) (since C++17)
template< class T, class U, class... Args >
constexpr std::optional<T> make_optional( std::initializer_list<U> il,
                                          Args&&... args );
(3) (since C++17)
1) Creates an optional object from value.
Equivalent to return std::optional<std::decay_t<T>>(std::forward<T>(value)).
This overload participates in overload resolution only if T is deduced from value.
2) Creates an optional object constructed in-place from args....
Equivalent to return std::optional<T>(std::in_place, std::forward<Args>(args)...);.
3) Creates an optional object constructed in-place from il and args....
Equivalent to return std::optional<T>(std::in_place, il, std::forward<Args>(args)...);.

These overloads participate in overload resolution only if the constraints of the corresponding std::optional constructor are satisfied.

Parameters

value - the value to construct optional object with
il, args - arguments to be passed to the constructor of T

Return value

As described above.

Exceptions

Throws any exception thrown by the constructor of T.

Notes

T need not be movable for overloads (2,3) due to guaranteed copy elision.

Example

#include <iomanip>
#include <iostream>
#include <optional>
#include <string>
#include <vector>

int main()
{
    auto op1 = std::make_optional<std::vector<char>>({'a', 'b', 'c'});
    std::cout << "op1: ";
    for (char c : op1.value())
        std::cout << c << ',';
    
    auto op2 = std::make_optional<std::vector<int>>(5, 2);
    std::cout << "\nop2: ";
    for (int i : *op2)
        std::cout << i << ',';
    
    std::string str{"hello world"};
    auto op3 = std::make_optional<std::string>(std::move(str));
    std::cout << "\nop3: " << std::quoted(op3.value_or("empty value")) << '\n';
    std::cout << "str: " << std::quoted(str) << '\n';
}

Possible output:

op1: a,b,c,
op2: 2,2,2,2,2,
op3: "hello world"
str: ""

Defect reports

The following behavior-changing defect reports were applied retroactively to previously published C++ standards.

DR Applied to Behavior as published Correct behavior
LWG 3627 C++17 the constraints of the std::optional constructor were not propagated for overload (1) propagated

See also

constructs the optional object
(public member function) [edit]