Skip to Content
C++ High Performance
book

C++ High Performance

by Viktor Sehr, Björn Andrist
January 2018
Intermediate to advanced
374 pages
9h 53m
English
Packt Publishing
Content preview from C++ High Performance

The std::variant

If we can trade off the ability to store any type in the container and, rather, concentrate on a fixed set of types declared at the container initialization, then std::variant is a better choice.

The std::variant has two main advantages over std::any:

  • It does not store its contained type on the heap (unlike std::any)
  • It can be invoked with a polymorphic lambda, meaning you don't explicitly have to know its currently contained type (more about this in the later sections of this chapter)

The std::variant works in a somewhat similar manner to a tuple, except that it only stores one object at a time. The contained type and value is the type and value you assigned it last. Look at the following image:

Tuple of types versus ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ High Performance - Second Edition

C++ High Performance - Second Edition

Björn Andrist, Viktor Sehr
Advanced C++

Advanced C++

Gazihan Alankus, Olena Lizina, Rakesh Mane, Vivek Nagarajan, Brian Price
C++ In a Nutshell

C++ In a Nutshell

Ray Lischner
C++ Cookbook

C++ Cookbook

D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell

Publisher Resources

ISBN: 9781787120952Supplemental Content