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
}
}
_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);
work.join();
}
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;
}
Prints
57
The declaration of your function assign_threads_instructions
takes a single parameter: _instr
wich is of type void* (*_instr) (int)
, ie :
pointer to function taking an
int
and returning pointer tovoid
.
The unnecessary naming of the int
inside the type has no effect other than readability.
Using modern C++ syntax makes this more clear.
using callback_t = std::add_pointer_t<void*(int)>;
bool assign_threads_instructions(callback_t instr) { /* ... */ }
The obvious answer is that you must pass the value along with the callback to your function.
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.