使用纯虚拟成员的地址进行虚拟呼叫。这合法吗? [英] Virtual Calls using address of pure virtual member. Is it legal?
问题描述
我读回来(可能是在c.l.c ++。版主),虚拟函数调用可以被模板化。我尝试过以下几行。
I read sometime back (probably on c.l.c++.moderated) that virtual function calls can be templatized. I tried something on the following lines.
#include <iostream>
template<class T, class FUN>
void callVirtual(T& t, FUN f){
(*t.*f)();
}
struct Base{
virtual ~Base(){}
virtual void sayHi()=0;
};
struct Derived : public Base{
void sayHi(){
std::cout << "Hi!" << std::endl;
}
};
void Test(){
Base* ptr = new Derived;
callVirtual(ptr,&Base::sayHi);
}
int main()
{
Test();
return 0;
}
Output:
Hi!
虽然在编译时给出了纯虚基本成员方法的地址,但是模板化的方法调用了正确的方法运行。
标准C ++中是否合法获取纯虚拟会员的地址?
The templatized method though given the address of pure virtual base member method at compile time calls the correct method at runtime. Is it legal in standard C++ to take address of a pure virtual member?
提前致谢
EDIT-1:我删除了问题的第二部分'它是如何工作的?'。看起来这就引起了人们的注意。
EDIT-1: I removed the second part of the question 'how does it work?'. Looks like that is what is catching attention.
EDIT-2:我搜索了clc ++。版主并遇到了这个链接( http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread / 5ddde8cf1ae59a0d )。由于标准不限制它,所以达成共识似乎是有效的。
EDIT-2: I searched c.l.c++.moderated and came across this link (http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/5ddde8cf1ae59a0d). The consensus seems like since the standard does not restrict it, it is vaild.
EDIT-3:阅读代码项目文章后(感谢ovanes),我认为编译器会做一些魔术。由于虚函数是通过vtable(特定于编译器)实现的,因此获取虚函数的地址总是会给出vtable中的偏移量。根据所使用的'this'指针,调用适当的函数(其地址位于偏移量)。我不确定如何证明这一点,因为标准没有说明任何内容!
EDIT-3: After reading the codeproject article (thanks to ovanes), i am thinking that the compilers do some magic. Since virtual functions are implemented via vtable (which is compiler specific), taking address of a virtual function always gives the offset in the vtable. Depending on the 'this' pointer used, the appropriate function (whose address is at the offset) is called. I am not sure how to vindicate this though as the standard does not say anything abt it!
推荐答案
以下文章广泛讨论成员C ++中的函数指针,它们是如何实现的以及缺陷在哪里。它还处理虚拟成员函数指针等等。我想它会回答你的所有问题。
This following article extensively discusses member function pointers in C++, how they are implemented and where are the flaws. It also handles virtual member function pointers and much more. I think it will answer all your questions.
http://www.codeproject.com/KB/cpp/FastDelegate.aspx
它还展示了如何在C ++中实现委托您可能陷入的陷阱。
It also shows how to implement delegates in C++ and what pitfalls you might trap in.
有善意的问候,
Ovanes
这篇关于使用纯虚拟成员的地址进行虚拟呼叫。这合法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!