'std::make_optional' is a C++17 library function that creates an 'std::optional' object containing a value of the specified type. If the provided value is a reference, it will be stored as a copy.

The syntax of 'std::make_optional' is as follows:

template< class T >
constexpr std::optional<std::decay_t<T>> make_optional( T&& value );

Here, 'T' is the type of the value to be stored in the 'std::optional' object. The function takes a single argument 'value' which is the value to be stored in the 'std::optional' object. The type of 'value' can be a reference or an rvalue.

The function returns an 'std::optional' object containing the specified value. If the value is a reference, a copy of the value is stored in the 'std::optional' object. If the value is an rvalue, it is moved into the 'std::optional' object.

Example usage:

#include <iostream>
#include <optional>

int main() {
    auto opt1 = std::make_optional<int>(42);
    auto opt2 = std::make_optional<std::string>('hello');

    std::cout << opt1.value() << ' ' << opt2.value() << std::endl;

    return 0;
}

Output:

42 hello
C++17 std::make_optional: Creating std::optional Objects

原文地址: https://www.cveoy.top/t/topic/nsGz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录