Hi team
I find I often do this in C, for me, it's a better way to do swich and case if the list is very long:
How do you do similar thing in C++ in a class with template or virtual function or something??
I find I often do this in C, for me, it's a better way to do swich and case if the list is very long:
C:
void foo1();
void foo2();
void foo3();
// ...
typedef struct mylist{
uint8_t val;
void (*cb)(void);
}mylist_t;
int main(int argc, char **argv){
const mylist_t list[] = {
{.val = 0, .cb = foo1},
{.val = 4, .cb = foo2},
{.val = 9, .cb = foo3},
// ...
};
for(uint8_t i = 0; i < LIST_SIZE; i++){
if (list[i].val == SOME_INPUT)
list[i].cb();
}
}
C++:
class Test{
public:
Test(){
// build the value and list with
// some kind of template??
list.push_back(some_val, foo1);
list.push_back(some_val, foo2);
// ...
}
void run(){
for(mylist &item: list){
if (item.val = USER_INPUT)
item.cb();
}
}
private:
mylist list
void foo1(){ /* do stuff */ }
void foo2(){ /* to stuff */ }
}