2 ms·
That… doesn’t make any sense? The size of an optional<T> is `sizeof T + 1` because it needs a boolean for the set/unset flag. The size of a variant is… the sa
by masklinn 2y ago
That… doesn’t make any sense?
The size of an optional<T> is `sizeof T + 1` because it needs a boolean for the set/unset flag.
The size of a variant is… the same, at least, because it needs to store a discriminator integer (apparently both gcc and clang do optimise to a byte when there are less than 256 variants).
Or do you mean adding a monostate to an existing variant rather than wrap that variant into an `optional`? In which case you should fix your example (and provide a version wrapped in an optional) because they’re very confusing.
- jcelerier 2y agoI don't understand what's confusing with my example aha. Current situation: you have std::variant<int, whatever> x; you now want to discriminate on whenever x has been initialized explicitly or not, the two cases I posted: // case 1 std::variant<int, whatever> x; // case 2 std::variant<int, whatever> x = 0; you have two options: option A: does not needlessly increase sizeof, does not add indirection penalty upon access: std::variant<std::monostate, int, whatever> x; option B: needlessly increases sizeof, adds indirection penalty upon access (mostly relevant when compiling in debug mode without inlining if you still want to have a semblance of performance): std::optional<std::variant<int, whatever>> x;