I know that the C++ standard library has a unit type - I've seen it before - but I can't remember what it's called. It starts with an "m", I know that much, and it is equivalent to this definition:
struct Unit {};
Basically, a unit type is a type with only one distinct value - as contrasted with void
which has zero values and bool
which has two.
If you must know, my particular use case was regarding the constructors of a template class with a union member. It pretty much looks like this:
template<typename T>
struct foo {
union {
T t;
std::string str;
} data;
foo(T const& t) {
data.t = t;
}
foo(std::monostate unused, std::string const& str) {
data.str = str;
}
};
In order to be able to distinguish the two constructors from one another, should T
be equal to std::string
, a sentry argument in the second constructor is needed. void
won't work of course, and bool
wouldn't make sense because there would be no difference between passing in true
vs false
- what was needed was a unit type.
It's called std::monostate
(Since C++17). It also overloads the ==
operator to return true, as well as some other operators, so that all instances of std::monostate
are equal.