Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tagged unions (aka variant) in C++ with the same type multiple times

I need to create an union, but 2 members of the union would have the same type, thus I need a way to identify them. For example in OCaml :

type A = 
  | B of int
  | C of float
  | D of float

Boost.Variant doesn't seem to support this case, is there a known library which supports that ?

like image 363
maattdd Avatar asked Jul 18 '13 15:07

maattdd


People also ask

What is tagged union in C?

In computer science, a tagged union, also called a variant, variant record, choice type, discriminated union, disjoint union, sum type or coproduct, is a data structure used to hold a value that could take on several different, but fixed, types.

Which union contains a tag for type checking?

A tagged union declaration looks just like a C union, except that it you must specify the @tagged qualifier when declaring it. For example: @tagged union Foo { int i; double d; char *@fat s; }; The primary difference with C unions is that a tagged union includes a hidden tag.

How does STD variant work?

std::variant (C++17) A std::variant is a type-safe union. An instance of std::variant has a value from one of its types. The value must not be a reference, C-array or void. A std::variant can have one type more than once.


1 Answers

If you want to do this, I think your best option is to wrap the same-but-different-types into a struct which then lets the boost variant visit the proper one:

struct Speed
{
    float val_;
};

struct Darkness
{
    float val_;
};

You might be able to use BOOST_STRONG_TYPEDEF to do this automatically but I'm not sure it's guaranteed to generate types legal for use in a union (although it would probably be fine in a variant).

like image 117
Mark B Avatar answered Oct 01 '22 03:10

Mark B