Mostafa Talebi Mostafa Talebi - 1 year ago 62
C++ Question

How to access a parameter of a passed-as-pointer function in c++

I have a mother function which accepts a function as its pointer. The passed function, accept an integer value X. Inside the mother function, I like to access integer X. How should I do it? The following throws undefined error:

bool assign_threads_instructions(void* (* _instr)(int socket_fd) )

int pool_size = get_threads_pool_size();
for(int i = 0; i < pool_size; i++)
threads_pool[i] = std::thread(_instr, socket_fd); // here I access the socket_fd parameter throws undefined error

Answer Source

_instr is the (possible) address of a function which has an int argument because void* (* _instr)(int socket_fd) declares a pointer named _instr which can point to a function returning void* and taking a single int argument named socket_fd. Thus, there is no socket_fd variable since you cannot (at least not as simply as through a function pointer) pass a callable packed with arguments.

You could either pass that value in seperately:

bool assign_threads_instructions(void* (* _instr)(int), int _fd)
    std::size_t pool_size = get_threads_pool_size();
    for(std::size_t i = 0; i < pool_size; ++i)
        threads_pool[i] = std::thread(_instr, _fd);

or have a template assign_threads_instructions function that has a to-be-deduced argument and use std::bind to generate a callable packed with the desired value.

std::bind example:

if you have an assign function template like:

template<class F>
void assign_stuff(F&& _f)
  std::thread work(_f);

you can use it to pack callbacks and values together into a single argument via std::bind:

void f(int& x)
  x = x + 2;
int main() 
  int q = 55;
  assign_stuff(std::bind(&f, std::ref(q)));
  std::cout << q << "\n";
  return 0;



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download