Library feature: std::variant

code

Syntax

std::variant is a modern, safer alternative to the old unions.

What are the differences?

  • std::variant is type-safe: the variant knows what type it currently holds – but needs more memory space in order to do so
  • std::variant calls the destructor of the object when it changes its type

Fetching the current value

In order to get the current value, we need to use std::get and use the index() function which contains the current index.

In case we use std::get and use a value different than the current index, we will receive a std::bad_variant_access exception instead.

 

Interogating the current type without exception

std::holds_alternative<type> returns a bool and can be used to verify whether a variant contains the current type or not.

 

 

 

Leave a comment

Your email address will not be published.