C++Builder Tutorial: Easily Learn To Use optional In Modern C++ On Windows

FireWind

Свой
Регистрация
2 Дек 2005
Сообщения
1,957
Реакции
1,199
Credits
4,009
Tutorial: Easily Learn To Use optional In Modern C++ On Windows
February 11, 2021 By Yilmaz Yoru

Для просмотра ссылки Войди или Зарегистрируйся (std: :tional) manages an optional contained value, i.e. a value that may or may not be present. This class template comes with C++17 standard, it is used with CLANG and other C++ compilers which has this standard. A common use case for optional is the return value of a function that may fail. Any instance of optional<T> at any given point in time either contains a value or does not contain a value. If an optional<T> contains 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.

Для просмотра ссылки Войди или Зарегистрируйся supports C++17 standards with its CLANG compiler and Bcc Compiler. Optional can be used to define any type of variables as below;
C++:
std::optional<int> a(5);
std::optional<int> b
An optional variable can be checked by has_value() method if it has a value or not.
C++:
if (a.has_value()) { }
Value optional variable can be obtained by value() property and or value_or(0) method that returns 0 if no value. This C++ Builder VCL Windows application example below explains all;
C++:
#include <vcl.h>
#include <windows.h>
#include <optional>

#pragma hdrstop
#pragma argsused

#include <tchar.h>
#include <stdio.h>

int _tmain(int argc, _TCHAR* argv[])
{
std::optional<int> a(5);
std::optional<int> b;

if (a.has_value())
        {
int z = a.value() + b.value_or(0); // *deref, or .value()
std::cout << z;
}

getchar();
return 0;
}