简体   繁体   中英

Array of pointers to functions C++

I have 3 functions with the same signature. I need to initialize an array with pointers to functions. I have:

typedef void(*sorting_func) (int* a, int n);

and functions:

class Sortings {
public:
    static void bubble_sort(int a[], int n);
    static void bubble_aiverson_1(int a[], int n);
    static void bubble_aiverson_2(int a[], int n);
};

I need an array with pointer in this class to use like this:

Sortings::array[0]...

Functions can be not static.

You could use a vector of std::function , ie

std::vector<std::function(void(int*,int)>> sortingFunctions;

Then, depending on the case you can directly push back free functions, or use a lambda to push back a member function the following way:

//Capturing `this` in the lambda implies the vector is a member of the class
//Otherwise, you must capture an instance of the class you want to call the 
//function on.
std::function<void(int*,int)> myMemberFunction = [this](int* a, int n){
    this->memberFunction(a,n);
}

sortingFunctions.push_back(myMemberFunction);

assuming you create the vector in a member function of your Sorting class.

See a live example here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM