简体   繁体   中英

Pass specialized function pointers in c++

I am working a with a c library inside my c++ code. Their API requires me passing a certain function pointer with a given signature. Let's say it's something like the following:

typedef int (*api_fun_t)(int);

What I want to be able to do is to pass function pointers that depend on certain parameters that are determined at runtime. Initially I thought of defining something like the following:

api_fun_t my_specialized_fun(int param){
    int fun(int x){
        // decide what to do based on param
    }
    return fun;
}

but problem c++ does not allow nested function definition. Next I figured I can achieve this via templates like the following

template <int param>
fun (int x){
    //decide what to do based on param
}

Is there any other way of doing this that does not involve global and/or static variables?

Use C++11 lambdas instead of nested functions. Eg:

typedef int (*api_fun_t)(int);

api_fun_t my_specialized_fun(int param){
   return [](int x) {x++; return x;};
}

Assuming the API allows you to pass a user parameter (as all well designed C-style callback APIs do), use a struct to hold the data, and pass a pointer to it as the parameter. You can then use the member data of the struct or call a member function as appropriate. You will have to make sure the lifetime of the struct is long enough.

If the API does not allow you to pass a user parameter, your only option is a global variable, thread local if multithreading is an issue. And write an angry email to the designer of the API.

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