将void *转换为std :: function [英] casting void* to std::function
问题描述
我有一个问题。我正在尝试将void *转换为std :: function。
这只是一个简单的示例,所有建议都会受到赞赏
I have an issue. I'm trying to convert a void* to std::function. This is just a simple example, any suggestions will be appreciated
#.h file
class Example {
public:
Example();
int foo(void* hi);
int fooFunc(std::function<int(int, int)> const& arg, int x, int y) {
foo(arg.target<void*>(), x, y);
return 2;
}
};
#.cpp file
Example::Example() {
}
int Example::foo(void * func, int x, int y)
{
//cast back to std::function
func(x, y);
std::cout << "running in foo: " << a << "\n";
return a;
}
我尝试过的每次投射均无效。
Every casting i tried did not work.
我知道我可以在此示例中发送 std :: function
,但这是为更大的对象而设计的,我正在研究一个示例在这里工作。
I know i can send a std::function
in this example, but it's for something bigger and i'm working on an example to make it work here.
void *
的全部含义是,在这些情况下,有时您不知道会收到什么,然后将其转换为所需的特定用法。
The whole meaning of void*
, is for sometimes to use it, in these situations, when you don't know what you will receive, and then cast it to the specific usage you need.
谢谢!
推荐答案
您不能。
您可以将数据指针强制转换为 void *
,然后返回到与之相同的指针类型。 std :: function
不是指针类型,因此强制类型转换在静态上是无效的,并且与开始时的操作不同。您已经从类型为 void(*)()
的 .target
开始,但这不是数据指针,而是函数指针,因此将其强制转换为 void *
并返回是实现定义的。
You can cast a data pointer to void*
and then back to the same pointer type you have started with. std::function
is not a pointer type, so the cast is statically invalid, and it's not the same thing you have started with. You have started with a .target
of type void(*)()
but it's not a data pointer, it's a function pointer, so casting it to void*
and back is implementation-defined.
您可以:
- 忽略该问题,并强制转换为
void(*)()
。将在大多数(但不是全部)平台上工作。 - 使用
void(*)()
代替void *
作为通用函数指针(可以将其强制转换为其他函数类型)。 - 使用C ++提供的任何工具来完全避免强制转换。
- Ignore the issue and cast to
void(*)()
anyway. Will work on most (but not all) platforms. - Use
void(*)()
instead ofvoid*
as a universal function pointer (you can cast it to other function types). - Use whatever tools C++ offers to avoid the cast altogether.
这篇关于将void *转换为std :: function的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!