How to implement union | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

How to implement union

Hello We all know that union allow us to have different data type and at a time only one memory address is allocated. I tried to replicate the same and thought to declare template class with template type data member as public member. But while instantiating object , we need to provide datatype for template which is not like union. So , can anyone would plz give me some hint of how to implement union by our own ?

30th Jul 2020, 4:30 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
1 Answer
+ 4
What you're ( probably ) talking about is an std::variant. It uses a variadic template to allow you to define the types. I've never tried to implement one myself so all I can say is check out the gcc source code for it to get the general idea: https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/include/std/variant And good luck.
30th Jul 2020, 4:49 PM
Dennis
Dennis - avatar