Created
June 20, 2025 19:13
-
-
Save xealits/16969cf0be0fa5e8595e4577b99e9d7e to your computer and use it in GitHub Desktop.
FSM functions (void*)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
struct FuncPtr; | |
typedef FuncPtr(Func)(int); | |
struct FuncPtr { | |
void *func; | |
FuncPtr(Func& f) : func{(void *) &f} {}; | |
FuncPtr operator()(int x) { return ((Func *)func)(x); } | |
}; | |
// return self: | |
FuncPtr func_foo(int x) { | |
std::cout << "func_foo " << x << "\n"; | |
return func_foo; | |
} | |
// return each other (like FSM states): | |
// error: illegal initializer (only variables can be initialized) | |
// Func func_baz = nullptr; | |
Func func_baz; | |
FuncPtr func_bar(int x) { | |
std::cout << "func_bar " << x << "\n"; | |
//return {nullptr}; | |
// error: no matching constructor for initialization of 'FuncPtr' | |
return func_baz; | |
} | |
FuncPtr func_baz(int x) { | |
std::cout << "func_baz " << x << "\n"; | |
return func_bar; | |
} | |
int main() { | |
func_foo(3)(5)(7); | |
std::cout << "\n"; | |
func_bar(3)(5)(7); | |
//FuncPtr null{nullptr}; | |
// error: no matching constructor for initialization of 'FuncPtr' | |
//null(4); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Godbolt link.