I wanna write a method taking different type of method pointers using argument polymorphism. I thought union will be a good idea in this situation. However, I don't know how to reference to the correct union instance using method argument.
#include <iostream>
union Method {
struct {
void (*a)();
void (*b)(int);
};
};
struct Item {
char c;
Method m;
};
int8_t menu_size = 0;
void add_item(Item menu[], Item item) {
int8_t index = 0;
bool exists = false;
do {
if (menu[index].c == item.c) exists = true;
++index;
} while (menu[index].c == item.c);
//
if (exists) {
menu[index - 1] = item;
} else {
menu[menu_size] = item;
++menu_size;
}
}
void hello();
void ret(int);
int main(void) {
Item menu[2];
add_item(menu, (Item){'h', &hello});
add_item(menu, (Item){'r', &ret});
menu[0].m();
menu[1].m(5);
return 0;
}
void hello() {
std::cout << "Hello, World!\n";
}
void ret(int i) {
std::cout << i << "\n";
}