gpt4 book ai didi

c++ - 为什么临时成员函数不绑定(bind)到正确的类型?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:26:11 26 4
gpt4 key购买 nike

假设我们有以下基类和派生类:

#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, char** argv) {
void (Porsche::*ptr)(void) = &Porsche::Drive;
Function(&Porsche::Drive, 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)- 因此比较结果为真。 comeau web compiler遵循此解释并编译您的代码。

关于c++ - 为什么临时成员函数不绑定(bind)到正确的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1440418/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com