optional用途如其名,它可以容纳一个对象值或是为空。典型的应用情景是函数调用时,如需根据条件返回一个对象(有效)或默认对象(无效),若该对象构造成本很高(资源分配等),可用optional返回一个空对象,提高效率。
例如:
1 template <typename T> 2 std::optional<T> getValueOptional(const std::size_t index, const std::vector<T> &values) 3 { 4 if (index >= values.size()) 5 return {}; 6 7 auto it{ values.begin() }; 8 std::advance(it, index); 9 return *it; 10 } 11 12 template <typename T> 13 T getValue(const std::size_t index, const std::vector<T> &values) 14 { 15 if (index >= values.size()) 16 return T{}; 17 18 auto it{ values.begin() }; 19 std::advance(it, index); 20 return *it; 21 } 22 23 // test optional 24 std::vector<int> values{ 1,2,3,4,5 }; 25 if (auto val{ getValueOptional(1, values) }) { 26 std::wcout << val.value() << std::endl; 27 }