[英]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?
传递的函数接受整数X。在母函数内部,我喜欢访问整数X。应如何做? 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
. _instr
是具有int
参数的函数的(可能)地址,因为void* (* _instr)(int socket_fd)
声明了一个名为_instr
的指针,该指针可以指向返回void*
的函数,并接受一个名为socket_fd
int
参数。 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. 因此,没有
socket_fd
变量,因为您不能(至少不像通过函数指针那样简单)传递带有参数的可调用对象。
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. 或具有一个
assign_threads_instructions
待推论参数的模板assign_threads_instructions
函数,并使用std::bind
生成具有所需值的可调用包装。
std::bind
example: std::bind
示例:
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: 您可以使用它通过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
57
The declaration of your function assign_threads_instructions
takes a single parameter: _instr
wich is of type void* (*_instr) (int)
, ie : 函数
assign_threads_instructions
的声明采用一个参数: _instr
的类型为void* (*_instr) (int)
, 即 :
pointer to function taking an
int
and returning pointer tovoid
.函数的指针接受一个
int
并返回指向void
指针。
The unnecessary naming of the int
inside the type has no effect other than readability. 类型内
int
的不必要命名除了可读性外没有其他作用。
Using modern C++ syntax makes this more clear. 使用现代C ++语法可以使这一点更加清楚。
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. 显而易见的答案是,您必须将值和回调一起传递给函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.