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++ |
Particle Swarm Optimization (PSO) is an optimization technique inspired by the collective behavior of natural organisms like birds or fish. It was introduced by James Kennedy and Russell Eberhart in 1995. In PSO, a population of candidate solutions, called particles, moves through the search space to...
16 min read
This method is mainly used to get the minimum possible values that this uniform_real_distribution can generate. The <random> header has to be included for using this function in the program. The <random> header will be a good source for generating random numbers. One of its components...
4 min read
The exponential search is a strong algorithm for already sorted arrays. Its efficiency comes from a strategic combination of exponential growth and binary search techniques. The algorithm starts by shooting the array with exponentially increasing indices until it has a probable home of that target value....
10 min read
Introduction: Pattern printing is a fundamental concept in programming that helps improve logical thinking and understanding of nested loops. One specific type of pattern is the inner reducing pattern, where the number of elements in each row decreases progressively as you move downward. In this pattern, you...
11 min read
Introduction HITS is a link analysis algorithm used predominantly in web search; it was stemming from the work of Jon Kleinberg and the algorithm is named Hyperlink-Induced Topic Search. Unlike PageRank, which considers overall popularity, HITS identifies two types of pages: hubs and authorities. Any given...
14 min read
In this article, we will discuss the D'Esopo-Pape Algorithm in C++ with its psecudocode and examples. Introduction In graph theory, the D'Esopo-Pape Algorithm, or DP Algorithm is a strong way to solve the Single Source Shortest Path (SSSP) problem. With non-negative edge weights, it effectively calculates the shortest...
6 min read
In this article, we will discuss the problem of finding the greatest component size in a Graph generated by connecting non-co-prime nodes through C++. The nodes of graphs are connected together through the edges. The elements of the graph are a subset of values that form...
5 min read
Overview of Mirroring a C++ N-ary Tree Trees are essential data structures in computer science and programming because they effectively organize and safeguard hierarchical data. N-ary trees are unique among the many tree varieties in that they can contain more than one child node over each parent,...
6 min read
A fundamental problem in algorithmic problem solving is the surpasser count, which measures the relative ordering of elements of an array. It is computing for each element in an array the number of elements to its right that are strictly greater than that element. It...
16 min read
Introduction In different fields of computer science and mathematics, modular arithmetic is a very essential concept. Modular multiplicative inverse is one of its core concepts. In this article we will explore what modular multiplicative inverse is, why it is important and how to calculate it efficiently using...
9 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