std::variant in C++ 1710 Feb 2025 | 4 min read C++17 has several valuable features that enhance the language's expressiveness and flexibility. The "std::variant", a powerful tool for handling variant types. Std::variant present in <variant> header, and it is a type-safe union that can store different time values. It represents a type-safe, stack-based, discriminated union. Unlike the traditional unions, which do not have type safety and exhibit undefined behaviour, std::variant ensures that the type of the stored value is always known at runtime, making it safer and more reliable. The "std::variant" is useful where the value type may vary, and the code needs to adapt accordingly. It ensures that only one specified type can be stored at a given time. How it is useful?
Example 1:Let us take a simple program to illustrate the std::variant in C++. Output: ![]() Explanation:In this program, the variant named myVariant is declared to hold values of different types: int, double, and string. So, three different values are assigned to the variant. First, the whole number 42 is assigned, then the decimal number is assigned, and a string is assigned. The program will print the types and values of the variant after each assignment. This variant feature allows a single variable to adapt to various data types, which provides a convenient and type-safe way to work with different scenarios in Cpp programming. Example 2:Let us take another simple program to illustrate the std::variant in C++. Output: ![]() Explanation:The program demonstrates using std::variant to handle scenarios where a variable can represent different types. The program defines two custom data types: BatteryPoweredDevice and SolarPoweredDevice. The variant named deviceVariant is declared to hold either BatteryPoweredDevice or SolarPoweredDevice values. A BatteryPoweredDevice instance is assigned to deviceVariant with a specified battery voltage in the main function. The program checks the active type within the variant using holds_alternative and then uses get to extract and print the relevant information. If the active type is BatteryPoweredDevice, it prints the battery voltage. If it's SolarPoweredDevice, it prints the solar panel efficiency. If the variant doesn't contain either of these types, it outputs a message indicating an unrecognized device type. This example illustrates the flexibility of std::variant in handling variant types, which makes it a valuable tool for scenarios where the type of a variable can dynamically change. In this case, it simulates a system dealing with different types of powered devices, showcasing how std::variant provides a type-safe way to manage diverse data structures within a single variable. Advantages:
Disadvantages
Conclusion:In conclusion, std::variant in C++17 is a powerful feature that enhances type safety and flexibility in handling variant types. It allows a single variable to adapt to different data types, making code more readable and expressive. While it introduces compile-time checks and simplifies the handling of variant types, it may have limitations in dynamic scenarios and can incur some overhead. Overall, std::variant is a valuable tool for managing diverse data structures within a single variable, offering a safer and more efficient approach to handling variant types in C++. Next TopicLCM of two numbers in C++ |
In this article, we will discuss with its implementation. Introduction: Face-down cards are arranged in a grid for the player to flip in the straightforward but entertaining card-flipping game. The goal of this game is to find matching pairs by turning the cards over two at a...
6 min read
In the realm of computer science and programming, searching algorithms are fundamental tools that facilitate the retrieval of data from various data structures. Among these, the linear search algorithm stands out for its simplicity and straightforward implementation. It sequentially checks each element in a list or...
20 min read
The Jump Pointer algorithm is an advanced method designed to optimize ancestor queries in tree structures. This algorithm enhances the efficiency of operations such as finding the lowest common ancestor (LCA) of two nodes. By preprocessing the tree, it assigns each node a set of "jump...
18 min read
Introduction: The Pen Distribution Problem is the classic combinatorial problem that appears in competitive programming, discrete mathematics and computer science. It is a great example of how real-life scenarios can be mathematically modeled. It is related to distributing a fixed number of identical items (pens) to...
18 min read
Introduction: Some movies have restrictions such as having age limits and even limiting the number of seats available in a movie theatre. So, on the basis of these criteria, can we figure out how many people can possibly watch the movie? We will speak about this issue...
11 min read
The domino and tromino tiling problem is a fascinating and classic problem in combinatorial mathematics and computer science. It involves determining the number of ways to cover a 2×n board entirely using dominoes and trominoes without any overlaps or gaps. This problem not only provides insights...
15 min read
In this article, we will discuss the with its mathematical properties, Recursive and optimized technique, and an example. What is the ? The Perrin sequence is an integer sequence that follows a specific recurrence relation. It is defined as follows: the first three terms are 3,...
8 min read
One of the good and efficient ways to solve an exact cover problem is by the Dancing Links algorithm or DLX. The process asks you to select subsets from a collection so that every element in the universal set is covered exactly once. Again, just like...
16 min read
A safe way to get the address of an object, whether it's an instance of a smart pointer or an element of a container, is to use the utility function std::to_address, which was added to the C++ Standard Library in C++17. In C++, getting the address...
4 min read
Introduction for : Rock-Paper-Scissors is a classic hand game that is often used as a simple decision-making tool. The game is usually played between two people, where each player simultaneously creates one of three shapes with an outstretched hand: rock, paper, and scissors. The rules are straightforward:...
13 min read
We request you to subscribe our newsletter for upcoming updates.

We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India

