#include <string> #include <iostream> class Car { public: void Drive() { std::cout << "Baby,can I drive your car?" << std::endl; } }; class Porsche : public Car { };
..还有以下模板功能:
template <typename T,typename V> void Function(void (T::*m1)(void),void (V::*m2)(void)) { std::cout << (m1 == m2) << std::endl; }
为什么使用GCC编译:
int main(int argc,char** argv) { void (Porsche::*ptr)(void) = &Porsche::Drive; Function(ptr,ptr); return 0; }
……但不是吗?
int main(int argc,char** argv) { void (Porsche::*ptr)(void) = &Porsche::Drive; Function(&Porsche::Drive,ptr); return 0; }
解决方法
int main(int argc,ptr); return 0; }
ptr的类型为void(Porsche :: *)(),但& Porsche :: Drive的类型为void(Car :: *)()(因为该成员在Car中找到,而不是在Porsche中).因此,调用的函数将这两个成员指针与这些类型进行比较,标准说
In addition,pointers to members can be compared,or a pointer to member and a null pointer constant. Pointer to member conversions (4.11) and qualification conversions (4.4) are performed to bring them to a common type. If one operand is a null pointer constant,the common type is the type of the other operand. Otherwise,the common type is a pointer to member type similar (4.4) to the type of one of the operands,with a cv-qualification signature (4.4) that is the union of the cv-qualification signatures of the operand types.
4.11描述了从void(Base :: *)()到void(Derived :: *)()的隐式标准转换.因此,比较会找到常见类型void(Porsche :: *)().对于Porsche类型的对象,两个成员指针都将引用相同的函数(即Car :: Drive) – 因此比较将产生true. comeau web compiler遵循此解释并编译您的代码.