how to do this in C++

Thread Starter

bug13

Joined Feb 13, 2012
2,002
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:
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();
    }
    
}
How do you do similar thing in C++ in a class with template or virtual function or something??
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 */ }
}
 

402DF855

Joined Feb 9, 2013
271
Your first example is valid C and C++. I'd recommend going back to switch/case as the compiler will probably generate more efficient code than your linear search.
 

Thread Starter

bug13

Joined Feb 13, 2012
2,002
Your first example is valid C and C++. I'd recommend going back to switch/case as the compiler will probably generate more efficient code than your linear search.
My actual list is something like this, so it's a lot tidier for me to put all the stuff in one central location for easier maintenance.
C++:
typedef struct mylist{
    uint8_t val1;
    uint8_t val2;
    uint8_t val3;
    // ...
    void (*cb)(void);
}mylist_t;
My first example work as it in C++, but it will start complaining once I put them in a class. The error is from the function pointer, I can't seem to know how to use a function pointer pointing to a method within a class, for example:
C++:
class Test{
            Test(){};
    void     run(void){
        void (*func_ptr)(void);
        func_ptr = foo1;
        func_ptr();     // this won't work
    }
    
    void foo1(void){};
    void foo2(void){};
}
 

402DF855

Joined Feb 9, 2013
271
This type of thing isn't done often, so I am just guessing, this might help:

void (Test::*func_ptr)(void);

You may then need to:

this->*func_ptr();
 
Top