I'm dealing with data items which basically can have three states:
- not present
- present and empty
- present and not empty (valid value)
I'm currently implementing it with a std::optional
to distinguish not present and present, and I use a special value to represent empty.
I've been thinking about using e.g. std::optional<std::optional<int>>
, but before going down that route: is there some generally agreed upon data type available which is able to better convey the conceptual information?
Update:
To add a bit more context as to why I want to do this: I'm dealing with external messages which have certain optional data fields, and each of these data fields has a specific reserved value meaning empty, plus a restricted set of allowed values. Further down the processing chain, I need to be able to distinguish the three different states for each item, as different actions are supposed to happen in each case.
Update 2:
The value can for example be a value which is able to represent empty (like e.g. std::string
), or a number, which has no concept of being empty.
CodePudding user response:
std::optional<std::optional<int>>
should give you what you want but may be syntactically difficult to use.
You could e.g. use a std::variant
with custom types.
namespace my {
struct missing{};
struct empty{};
template <typename T>
using data = std::variant<missing, empty, T>;
}
Or you could write a custom data class that behaves as you need it.