加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么成员函数temporaries不绑定到正确的类型?

发布时间:2020-12-16 04:58:15 所属栏目:百科 来源:网络整理
导读:假设我们有以下基类和派生类: #include string#include iostreamclass Car {public: void Drive() { std::cout "Baby,can I drive your car?" std::endl; }};class Porsche : public Car {}; ..还有以下模板功能: template typename T,typename Vvoid Func
假设我们有以下基类和派生类:
#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遵循此解释并编译您的代码.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读