banner
Matrix

Matrix

Abyss
email
github

Petty C++ - std::variant

std::variant is a union introduced in the C++17 standard. std::variant can store data of different types in a single variable while maintaining type safety, which traditional unions cannot provide.

Main Features#

Type Safety#

Using std::variant ensures that the correct type value is always accessed. If an incorrect type is accessed, it will throw a std::bad_variant_access exception.

Automatic Management#

std::variant and std::any can manage the creation and destruction of internal data, ensuring proper resource management.

Access Control#

Data in std::variant can be accessed through std::get (ensuring the correct type).

Can be used with visit#

std::visit can be used to operate on data stored in std::variant.

Example#

In this example, std::variant is used to store an int, a float, and a std::string. It demonstrates how to safely use std::get to access data in std::variant and how to use std::visit to apply functions or visitors to the stored values.

Real Environment#

This code shows how to use std::variant and std::visit to handle different types of resources. Here, the ResourceManager::flipResource method takes a ResourceVariant parameter named resource and returns a ResourceVariant of the same type. This ResourceVariant is a std::variant type that can contain different resource types (such as IMAGE or Atlas).

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.