返回相同类型成员函数指针的成员函数指针
我想在 C++ 中声明一个成员函数指针,它返回相同的成员函数指针类型
这不起作用:
class MyClass {
public:
typedef FunctionPtr (MyClass::*FunctionPtr)();
}
有人知道解决方案吗?
I'd like to declare a member function pointer in C++, that returns the same member function pointer type
This doesn't work:
class MyClass {
public:
typedef FunctionPtr (MyClass::*FunctionPtr)();
}
Does someone know a solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
没有办法完全实现这一点。事实上,成员函数在这里没有区别:没有办法声明一个返回指向其自身函数类型的指针的普通函数。该声明将无限递归。
对于普通函数,您可以使用
void (*)()
类型作为“通用”函数指针类型(就像void *
通常用于数据类型一样) )。对于成员函数指针,其类型为void (A::*)()
。不过,您必须使用reinterpret_cast
来达到此目的。然而,这种用法(往返转换)恰好是定义reinterpret_cast
行为时的用法。当然,您将被迫使用强制转换来将指针与该类型相互转换。 AFAIK,有一些优雅的基于模板的解决方案,其中包含执行转换的中间临时模板对象。
您可能还想看看GotW 条目。
PS 请注意,该语言禁止使用
void *
类型作为函数指针的中间类型。虽然这种非法使用可能看起来对普通函数指针“起作用”,但它绝对没有机会与成员函数指针一起起作用。成员函数指针通常是大小大于void *
指针大小的非平凡对象。There's no way to achieve exactly that. In fact, member functions make no difference here: there's no way to declare an ordinary function that returns a pointer to its own function type. The declaration would be infinitely recursive.
In case of an ordinary function you can use the
void (*)()
type as an "universal" function pointer type (just likevoid *
is often used for data types). For member function pointers that would bevoid (A::*)()
type. You'd have to usereinterpret_cast
for that purpose though. However, this usage (a round-trip conversion) happens to be the one when the behavior ofreinterpret_cast
is defined.Of course, you'll be forced to use casts to convert the pointer to and from that type. AFAIK, there are elegant template-based solutions with an intermediate temporary template object that does the casting.
You might also want to take a look at this GotW entry.
P.S. Note, that using
void *
type as an intermediate type for function pointers is prohibited by the language. While such illegal use might appear to be "working" with ordinary function pointers, it has absolutely no chance to work with member function pointers. Member function pointers are normally non-trivial objects with size greater than the size ofvoid *
pointer.AndreyT 在 GotW #57 引用了最佳答案,所以我不妨在这里复制它:
AndreyT references the best answer at GotW #57, so I might as well replicate it here:
你想要做的事情是不可能的 - 函数的返回类型是函数本身的类型,这是未知的,所以它会导致无限循环。
What you're trying to do is not possible - the return type of the function is the type of the function itself, which is not yet known, so it leads to an infinite cycle.