What Is The New Optional Class Template In C++ 17?
The C++17 standard came with a lot of great features and std::optional was one of the main features of today’s modern C++. std::optional is a class template that is defined in the header and represents either a T value or no value. In this post, we explain, what is optional in modern C++ and how we can use it efficiently. What is the optional class template in C++ 17 and beyond? The std::optional feature is a class template that is defined in the header and represents either a T value or no value (which is signified by the tag type nullopt_t). In some respects, this can be thought of as equivalent to variant, but with a purpose-built interface. Here is the definition of the std::optional class template. template class optional; Optional can be used to define any type of variables as below. std::optional a(5); std::optional b; An optional variable can be checked by has_value() method if it has a value or not. if (a.has_value()) { } Here is another example that has a function with an optional return. std::optional testopt(std::string s) { if(s.length()==0) return {}; else return s; } as you see our function may return a string as an option or it may have no return value. A common use case for optional is the return value of a function that may fail. Any instance of optional at any given point in time either contains a value or does not contain a value. If an optionalcontains a value, the value is guaranteed to be allocated as part of the optional object footprint, i.e. no dynamic memory allocation ever takes place. Thus, an optional object models an object, not a pointer, even though operator*() and operator->() are defined. Is there a simple example about the optional class template in C++ 17? Here is a simple example about the std::optional, 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 #include #include int main() { std::optional a(5); // a = 5 std::optional b; // b has no value if (a.has_value()) { int z = a.value() + b.value_or(0); std::cout
