More precisely, the feature I want is like implicitly convert an enum to its subset enum and vice versa.
The code I wish it working:
enum class Human {
A = 1,
B = 2,
};
enum class Male { // subset of Human
A = Human::A,
};
enum class Female { // subset of Human
B = Human::B,
};
// some functions can handle all humans
void human_func(Human h) {
// ...
}
// some only take a subset of humans
void male_func(Male m) {
// ...
}
void female_func(Female m) {
// ...
}
// and user only uses values of Human as token
constexpr auto SOMEONE = Human::A;
int main() {
human_func(SOMEONE); // ok
male_func(SOMEONE); // also ok, Human::A implicitly converted to Male
female_func(SOMEONE); // failed, can't convert Human::A to Female.
}
But enum can not do the conversion. Now I have two options:
// 1. static_assert with template parameter
template <Human H>
void female_func() {
static_assert(H == Human::B);
// ...
}
// 2. manually convert it
#define _ENUM_TO_ENUM(e1, e2) \
static_cast<e2>(static_cast<std::underlying_type_t<decltype(e1)>>(e1))
void female_func(_ENUM_TO_ENUM(SOMEONE, Female)) {
// But this way the compiler does not check if the value is valid.
// I can put anything in.
// ...
}
So is there other techniques to accomplish this?
explicit
. Explicitly written code is easier to understand later when you need to maintain/debug and/or test your code.female_func
, why does it even take an argument if we already know it's for "females" by just reading its name?