Delaying initialization with std::optional

You might already be thinking that one potential use for std::variant would be to represent the notion of "Maybe I have an object, and maybe I don't." For example, we could represent the "maybe I don't" state using the standard tag type std::monostate:

    std::map<std::string, int> g_limits = {      { "memory", 655360 }    };    std::variant<std::monostate, int>    get_resource_limit(const std::string& key)    {      if (auto it = g_limits.find(key); it != g_limits.end()) {        return it->second;      }      return std::monostate{};    }    void test()    {      auto limit = get_resource_limit("memory");      if (std::holds_alternative<int>(limit)) {        use( std::get<int>(limit) );      } else {        use( some_default );      }    }

You'll be pleased to know that this is ...

Get Mastering the C++17 STL now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.