search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
Declare and initialize a variant
Check and access the current value
Handle all cases safely with std::visit
Deal with exceptions and special cases
Home Backend Development C++ How to use std::variant in C 17? (Type-Safe Union Tutorial)

How to use std::variant in C 17? (Type-Safe Union Tutorial)

Dec 31, 2025 am 01:11 AM

std::variant is a type-safe union introduced in C 17. It only holds one value of a specified type at the same time; it supports direct initialization, runtime type checking (holds_alternative), safe access (get_if) and generic access (visit). Implicit conversion is prohibited and recursive definitions need to be avoided.

How to use std::variant in C 17? (Type-Safe Union Tutorial)

std::variant is a type-safe union introduced in C 17 — it holds exactly one value from a set of allowed types at any time, and enforces compile-time safety so you can't accidentally read the wrong type.

Declare and initialize a variant

Specify the allowed types as template arguments. You can initialize it with any of those types:

  • Use direct initialization: std::variant v = 42;
  • Or use std::make_variant_alternative (rarely needed), or assignment: v = std::string{"hello"};
  • Default construction only works if the first alternative is default-constructible — std::variant defaults to an int (zero-initialized).

Check and access the current value

You must safely inspect what's stored before accessing it:

  • Use std::holds_alternative(v) to test if v currently holds type T .
  • Use std::get(v) to retrieve the value — throws std::bad_variant_access if T isn't active.
  • Prefer std::get_if(&v) , which returns a pointer: non-null if T is active, nullptr otherwise — no exception risk.

Handle all cases safely with std::visit

The most robust way to work with a variant is std::visit , which dispatches to the right handler based on the active type:

  • Pass a callable (lambda, function object, or function pointer) and the variant.
  • Lambda parameters should match each alternative — the compiler checks exhaustiveness if you use a generic lambda or explicitly list overloads.
  • Example: std::visit([](auto&& x) { std::cout works for any printable type in v ’s list.

Deal with exceptions and special cases

Variants are move-aware and exception-safe, but watch for pitfalls:

  • Assigning a new value may throw (eg, moving a std::string that allocates), but the variant stays in a valid state.
  • No implicit conversions — std::variant v = 3.14; won't compile. Use explicit construction or cast if intended.
  • Avoid recursive variants (eg, std::variant> ) — use indirection like std::unique_ptr instead.

The above is the detailed content of How to use std::variant in C 17? (Type-Safe Union Tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)