Skip to content

Instantly share code, notes, and snippets.

@xealits
Created June 20, 2025 19:13
Show Gist options
  • Save xealits/16969cf0be0fa5e8595e4577b99e9d7e to your computer and use it in GitHub Desktop.
Save xealits/16969cf0be0fa5e8595e4577b99e9d7e to your computer and use it in GitHub Desktop.
FSM functions (void*)
#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;
}
@xealits
Copy link
Author

xealits commented Jun 20, 2025

$ clang++ -std=c++11 -Wall -Wconversion function_returns_self_type_example.cpp 
$ ./a.out 
func_foo 3
func_foo 5
func_foo 7

func_bar 3
func_baz 5
func_bar 7

Godbolt link.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment