4 ms·
You don't see how variants improve readability over union+tag? Do you mean that you don't see a whole lot of difference below: std::variant<int, std::string>
by eMSF 6y ago
You don't see how variants improve readability over union+tag? Do you mean that you don't see a whole lot of difference below:
std::variant<int, std::string> setting;
setting = "foo"s;
setting = 1;
Compared with something like:
struct Setting {
Setting() { XXX }
~Setting() { XXX }
union {
string str;
int num;
};
enum Type { Str, Int, None };
Type tag;
};
Setting setting;
if (setting.tag != Setting::Str)
new (&setting.str) std::string;
setting.str = "foo";
setting.tag = Setting::Str;
if (setting.tag == Setting::Str)
setting.str.~std::string();
setting.str = 1;
setting.tag = Setting::Int;
- westwing 6y agoYou could put these behind overloaded operators and use them like the variant type. In any event, the really ugly part is matching, not construction or assignment.
- socialdemocrat 6y agoLooks like you are making things deliberately complicated. Here is an existing Variant type which existed long before modern C++ and which is easy to use: https://doc.qt.io/qt-5/qvariant.html https://doc.qt.io/qt-5/qvariant.html