What Is The Class Template Variant (std::variant) in C++ 17?

In C++ Builder 12, and modern C++ the std::variant is one of the powerful features that comes with C++17. The std::variant is a discriminated union that we can work with multiple data types. It represents a type-safe union and holds one of its types in definition.

What is the class template std::variant in C++ 17?

The std::variant is a class template defined in  header that represents a disjoint union (or discriminated union). A value of variant contains one of an A, a B, or a C at any one time. It can be used as a multi-type variable, for example, a variable can be a float, an int, or a string.

Here is the template definition since C++17:

Here is a simple example that shows how we can use it.

To get value of a variant we can use std::get (std::variant), here is how we can use it:

std::variant has many useful methods and properties that can be used in modern C++, such as index, valueless_by_exception, emplace, swap, get_if, visit, variant_size, variant_size_v, variant_npos, monostate, std::hash, and operators ( =, ==, !=, <, >, <=,>=,<=> )

Is there a full example about the class template variant in C++ 17?

Here is an example.

I should note that this feature can currently only be compiled with the new bcc64x compiler.

For more details about this feature in C++17 standard, please see these papers; P0088R3P0393R3P0032R3P0504R0P0510R0LWG 2901DR

What Is The Class Template Variant stdvariant in C++ 17

C++ Builder is the easiest and fastest C and C++ compiler and IDE for building simple or professional applications on the Windows operating system. It is also easy for beginners to learn with its wide range of samples, tutorials, help files, and LSP support for code. RAD Studio’s C++ Builder version comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for UIs.

There is a free C++ Builder Community Edition for students, beginners, and startups; it can be downloaded from here. For professional developers, there are Professional, Architect, or Enterprise versions of C++ Builder and there is a trial version you can download from here.