简体   繁体   中英

Translating Swift enums with associated values to C++

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 .)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM