指向成员函数的指针问题
在下面的代码中(请参阅评论):
#include "stdafx.h"
#include <iostream>
using std::cout;
struct Base
{
void fnc()
{
cout << "Base::fnc()";
}
};
struct Impl
{
void* data_;
Impl(void (Base::*fp)())
{
fp();//HERE I'M INVOKING IT - I'M DOING SOMETHING WRONG!
}
};
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
错误
“错误 1 错误 C2064:术语不计算为采用 0 个参数的函数” 为什么它不起作用以及如何修复它?
In code below (please see comment):
#include "stdafx.h"
#include <iostream>
using std::cout;
struct Base
{
void fnc()
{
cout << "Base::fnc()";
}
};
struct Impl
{
void* data_;
Impl(void (Base::*fp)())
{
fp();//HERE I'M INVOKING IT - I'M DOING SOMETHING WRONG!
}
};
int _tmain(int argc, _TCHAR* argv[])
{
return 0;
}
Error
"Error 1 error C2064: term does not evaluate to a function taking 0 arguments"
Why doesn't it work and how to fix it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
它不起作用,因为
fp
不是函数指针而是成员指针。如何修复它很简单,按照应该使用的方式使用它:
someinstance.*fp();
It doesn't work because
fp
is not a function pointer but a member pointer.How to fix it is easy, use it as it should be used:
someinstance.*fp();
问题是您将该函数作为自由函数调用,而实际上它不是。它是一个成员函数,您需要在对象的上下文中调用它:
Boost.Bind 提供了一种惯用的方法来解决这个问题:
您可以像这样定义
Impl
构造函数:如果只有
Impl
对象知道要调用该函数的对象,那么您可以使用 Boost.Bind 的占位符:然后
Impl
构造函数将类似于有时它是明智的使用模板接受函子的一侧:
因为这样客户端就可以传递任何成员函数,无论有没有 boost。但代价是您可能会遇到更难以理解的编译器错误消息。
The problem is that you are calling the function as a free function, when it isn't. It's a member function, and you need to call it in the context of an object:
Boost.Bind offers an idiomatic way to tackle this:
You can define the
Impl
constructor like so:If only the
Impl
object knows what object to call the function on, then you can use the placeholders of Boost.Bind:And the
Impl
constructor would then be similar toSometimes it's wiser to use templates in the side that accepts the functor:
because then the client can pass any member function, with or without boost. But the cost is that you might have harder-to-understand compiler error messages.
由于它是指向成员函数的指针,因此必须在对象上调用它并使用 ->* 或 .* 运算符来调用它。
Since it's a pointer to a member function, you must call it on an object and use the ->* or the .* operator to call it.
您需要一个基础来调用该函数。
您可能正在寻找更像是 bind() 和 function<> 的东西。这将允许您将实例和成员函数绑定到可以像函数一样调用的函子中。
You need a Base to call the function on.
You might be looking for something more like bind() and function<> that will allow you to bind an instance and member function into a functor that can be just called like a function.
您可以阅读此有关指向成员的常见问题解答功能。
他们特别强烈建议您为这些调用定义一个宏:
#define CALL_MEMBER_FN(object,ptrToMember) ((object).*(ptrToMember))
You could benefit from reading this FAQ regarding pointers to member functions.
Particularly they strongly recommend you define a macro for these calls:
#define CALL_MEMBER_FN(object,ptrToMember) ((object).*(ptrToMember))