Void Pointers and std::any

std::any vs std::variant

What's the difference between std::any and std::variant? When would I use one over the other?

Illustration representing computer hardware

std::any and std::variant are both ways to create a variable that can hold different types, but they work quite differently:

std::any can hold a value of any single type, and the type can be decided at runtime. It's like a type-safe void*.

std::any a = 42;
a = "hello";// OK, a now holds a string

std::variant holds a value that can be one of a fixed set of types, which must be specified at compile-time.

std::variant<int, string> v = 42;
v = "hello"; // OK, string is one of the types
v = 3.14; // Error: double is not one of the types

Use std::any when:

  • The type really can't be known at compile-time
  • You need to store any single value, but the type might change

Use std::variant when:

  • The type can be one of a limited set of known types
  • You need to store multiple types in the same variable or container
  • You want the type-safety and performance benefits of knowing the types at compile-time

Generally, prefer std::variant where possible. It offers better performance and type-safety. Only use std::any when the flexibility of runtime typing is truly necessary.

Answers to questions are automatically generated and may not have been reviewed.

A computer programmer
Part of the course:

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Free, unlimited access

This course includes:

  • 124 Lessons
  • 550+ Code Samples
  • 96% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved