|
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
| Member functions | ||||
| Observers | ||||
| Iterators | ||||
(C++26) | ||||
(C++26) | ||||
| Monadic operations | ||||
(C++23) | ||||
(C++23) | ||||
(C++23) | ||||
| Modifiers | ||||
| Non-member functions | ||||
make_optional | ||||
| Deduction guides | ||||
| Helper classes | ||||
| Helper objects | ||||
Defined in header <optional> | ||
template<class T> constexprstd::optional<std::decay_t<T>> make_optional( T&& value); | (1) | (since C++17) |
template<class T,class...Args> constexprstd::optional<T> make_optional( Args&&...args); | (2) | (since C++17) |
template<class T,class U,class...Args> constexprstd::optional<T> make_optional(std::initializer_list<U> il, | (3) | (since C++17) |
Contents |
| value | - | the value to construct optional object with |
| il, args | - | arguments to be passed to the constructor ofT |
The constructed optional object.
Throws any exception thrown by the constructor ofT.
T need not be movable for overloads(2,3) due to guaranteed copy elision.
#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: ""
constructs theoptional object(public member function)[edit] |