최대 1 분 소요

개요

  • 존재유무를 관리할 수 있는 클래스 템플릿
  • 레퍼런스를 저장하려면 reference_wrapper를 이용


예제

  • 코드
    #include <functional>
    #include <iostream>
    #include <map>
    #include <optional>
    #include <string>

    using namespace std;

    int main() {
    	map<int, string> m;
    	m.clear();
    	m[0] = "a";
    	m[1] = "b";

    	auto get = [&m](int key) -> optional<string> {
    		if (m.find(key) != m.end()) {
    			return m[key];
    		}

    		return nullopt;
    	};

    	cout << get(0).has_value() << endl;
    	cout << get(0).value() << endl;
    	cout << get(2).has_value() << endl;

    	cout << "------" << endl;

    	int a = 0;
    	optional<reference_wrapper<int>> o = ref(a);
    	cout << a << endl;
    	o->get() = 1;
    	cout << a << endl;

    	return 0;
    }
  • 실행 결과
    1
    a
    0
    ------
    0
    1