In Swift you can have an enum type with associated values.
enum Thing {
case num(Int)
case two(String, Double)
case other
}
var t: Thing = .num(123)
t = .two("a", 6.022)
t = .other
From what I'm reading, you can can do a similar thing in C by using std::variant
. It has less syntactic sugar.
But the compiler complains if you give void
to std::variant
, so how would you represent the other
case above? Maybe an ignored integer? Or is there better way to translate something like that enum type to C ?
std::variant<int, pair<string, double>, void> // error
std::variant<int, pair<string, double>, int> // okay
Compiler error from Clang:
... "variant can not have a void type as an alternative."
(If I wanted to refer to that variant as Thing
I could use a typedef or wrap it in a struct
.)
CodePudding user response:
Because void
cannot be instantiated, you'll need some stand-in type to represent void
.
You could make your own, struct void_t{};
, or you could use the std::monostate
which is provided in C 17 and later.