C++

C++ - Datatypes

std::optional, structural binding

Posted by Rico's Nerd Cluster on January 5, 2023

Optional

std::optional can specify if a value is valid or not. It has:

  • .has_value() to examine if it has value
  • .value() to retrieve the value
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <optional>
#include <iostream>
#include <vector>
using namespace std;

void test_optional(){
    auto get_ll = [](bool does_return)-> std::optional<size_t> {
        if(does_return) 
            return 1;
        else 
            return {};
    };
    cout<<get_ll(true).value()<<endl;
    if (get_ll(false).has_value()){
        cout<<"yay"<<endl;
    }
}

int main(){
    test_optional();
}

Structural Binding