Date: Fri, 1 Apr 2022 18:00:37 +0200
Hi,
I have a wild idea, which might or might not be useful, just curious if
anyone likes it. Basically enum classes could be enhanced with a built in
way to dispatch function calls based on their value, they could even set
next value effectively implementing a state machine:
enum class DispatchStuff(int Arg1, double Arg2) : int {
VALUE_1 {
std::cout << "VALUE_1 int:" << Arg1 << " dbl:" << Arg2 << std::endl;
*this = VALUE_2;
}
VALUE_2 {
std::cout << "VALUE_2 int:" << Arg1 << " dbl:" << Arg2 << std::endl;
*this = VALUE_1;
}
default {
throw InvalidValueException();
}
};
And this could be used as:
int main() {
DispatchStuff state{DispatchStuff::VALUE_1};
state(1, 3.14);
state(2, 10.0);
}
So it would be like a normal enum, but it would be callable, and had a
state. I know this can be done now, but the same can only be achieved by a
load of boilerplate, especially for large state enums.
I find it redundant to list the whole enum, then have a switch-case
function to handle the dispatching. And this is also error-prone, as with
new enum values the dispatch function also needs to be changed.
It might not worth it, just an idea.
Regards,
Gergely
I have a wild idea, which might or might not be useful, just curious if
anyone likes it. Basically enum classes could be enhanced with a built in
way to dispatch function calls based on their value, they could even set
next value effectively implementing a state machine:
enum class DispatchStuff(int Arg1, double Arg2) : int {
VALUE_1 {
std::cout << "VALUE_1 int:" << Arg1 << " dbl:" << Arg2 << std::endl;
*this = VALUE_2;
}
VALUE_2 {
std::cout << "VALUE_2 int:" << Arg1 << " dbl:" << Arg2 << std::endl;
*this = VALUE_1;
}
default {
throw InvalidValueException();
}
};
And this could be used as:
int main() {
DispatchStuff state{DispatchStuff::VALUE_1};
state(1, 3.14);
state(2, 10.0);
}
So it would be like a normal enum, but it would be callable, and had a
state. I know this can be done now, but the same can only be achieved by a
load of boilerplate, especially for large state enums.
I find it redundant to list the whole enum, then have a switch-case
function to handle the dispatching. And this is also error-prone, as with
new enum values the dispatch function also needs to be changed.
It might not worth it, just an idea.
Regards,
Gergely
Received on 2022-04-01 16:00:49