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 ?
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With