c++ void* 作为函数的参数
我在某个库中有这个函数:
class myConsole
{
void addCommand( std::string command, void* fn );
...
}
在我的类中我有这个函数:
void myApp::TestFn( const std::vector<std::string> & args )
{
// do something
}
在同一个类中我称之为:
void myApp::initApp( )
{
myConsole::getSingleton( ).addCommand( "FirstTest", &myApp::TestFn );
}
但这给了我这个错误:
错误 c2664 无法将参数 2 从 'void(__thiscall myApp::*)(const std::vector<_Ty>&)' 到 'void *'
我该如何解决这个问题?
提前致谢!
I have this function in some library:
class myConsole
{
void addCommand( std::string command, void* fn );
...
}
and in my class I have this function:
void myApp::TestFn( const std::vector<std::string> & args )
{
// do something
}
in the same class I call this:
void myApp::initApp( )
{
myConsole::getSingleton( ).addCommand( "FirstTest", &myApp::TestFn );
}
but this gives me this error:
error c2664 cannot convert parameter 2 from 'void(__thiscall
myApp::*)(const std::vector<_Ty>&)' to 'void *'
how can I solve this?
thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你无法解决这个问题。您无法可靠地将函数指针转换为
void *
并返回。(我建议您重新设计程序并远离
void*
;在 C++ 中实际上并不需要它。)You can't solve this. You can't reliably cast a function pointer to
void *
and back.(I suggest you redesign the program and stay clear of
void*
; there's no real need for it in C++.)这里的问题是您试图传递一个类方法,因为它是一个
void *
指针。这是不可能的。正确的方法是使用 void addCommand (std::string, void *) 方法的模板。像这样的东西
给了你C++中的回调原理,但我认为你需要比这个解决方案更灵活的东西,因为你实际上想自动选择回调将执行的命令(在本例中为
TestFn
)。The problem here is that you are trying to pass a class method as it were a
void *
pointer. This cannot be done.The right way of doing this is by using templates for the
void addCommand (std::string, void *)
method. Something likeThis gives you the callback principle in C++, but I think you need something more flexible than this solution, since you actually want to choose automatically the command that will be executed by the callback (in this case
TestFn
).您应该避免使用
void*
,尤其是在尝试使用函数指针时。我假设您只查看 myApp 类中的成员函数指针,并且您只对采用 const std::vector的成员函数指针感兴趣。 std::string> &args
作为参数。此 typedef 将创建适当的类型并将其命名为MemFunType
这是一个完整的示例(位于 ideone),其中有两个不同的成员函数您可能感兴趣,
TestFn
和TestFnBackwards
。这个示例可能不是很有用,但它提供了一些成员函数指针的示例。You should avoid
void*
, especially when trying to use function pointers. I'm going to assume that you are looking only at member-function pointers in themyApp
class, and that you are only interested in member-function pointers which takeconst std::vector<std::string> &args
as an argument. This typedef will create the appropriate type and call itMemFunType
Here is a complete example (on ideone), where there are two different member-functions you may be interested in,
TestFn
andTestFnBackwards
. This example probably isn't very useful, but it gives some examples of member-function pointers.