繁体   English   中英

gcc / clang上的模板出错,但MSVC上没有

[英]Error with templates on gcc/clang but not on MSVC

我在模板和可移植性方面遇到问题。 鉴于此MVCE:

#include <cstdio>

class C
{
public:
    void go()
    {
        printf("go\n");
    }
};

template<typename T>
class A
{
public:
    A(T* pInstance) : m_pInstance(pInstance)
    {
    }

protected:
    T* m_pInstance;
};

template<typename T>
class B : public A<T>
{
    using Base = A<T>;
public:
    B(T* pInstance) : A<T>(pInstance)
    {
    }

    void foo()
    {
        B::m_pInstance->go();
        C* a = nullptr;
        if (a == &B::m_pInstance)
        {
        }

    }
};

int main(int argc, char** argv)
{
    C c;
    B<C> b(&c);
    b.foo();
}

我收到错误:

main.cpp:37:9: error: invalid operands to binary expression ('C *' and 'C *A<C>::*')
                if (a == &B::m_pInstance)
                    ~ ^  ~~~~~~~~~~~~~~~
main.cpp:48:4: note: in instantiation of member function 'B<C>::foo' requested here
        b.foo();
          ^
1 error generated.

但是我不确定为什么要得到这个吗? 好的,我看到类型有何不同,但是为什么后者成为成员会导致此问题呢? Visual Studio(当然具有不同的模板引擎)处理相同的问题。

&B::m_pInstance是指向数据成员的指针。 您要么将其更改为

if (a == this->B::m_pInstance)

要么

if (a == B::m_pInstance)

如果你想为指针到成员你必须改变对它们进行比较a的类型,如:

    T* (A<T>::*a) = nullptr;

要么

    C* (A<C>::*a) = nullptr;

我不知道MSVC是如何处理的,但是它肯定是一个错误。

&B::m_pInstance恰好是形成指向成员的指针的语法。 您可以使用&(B::m_pInstance)消除它的歧义,以获取所需的普通成员访问权限,但这随后揭示了另一个问题:

main.cpp:37:15: error: comparison of distinct pointer types ('C *' and 'C **')
        if (a == &(B::m_pInstance))
            ~ ^  ~~~~~~~~~~~~~~~~~

我猜你真正想要的是if(a == B::m_pInstance)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM