c++ - gcc/clang 上的模板错误,但 MSVC 上没有

标签 c++ templates gcc visual-c++

我在模板和可移植性方面遇到问题。给定这个 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;

关于c++ - gcc/clang 上的模板错误,但 MSVC 上没有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48771307/

相关文章:

c++ - 如何在 CRTP 基类中根据 "op"实现 "op="?

templates - 如何在没有范围操作的情况下按键获取 map 值(htm/文本模板)?戈朗

c - 海合会: "warning: assignment from incompatible pointer type"

c++ - 在构造函数中分配数组时出错

c++ - const 指针作为 std::bind 参数

c++ - 无法解决一组变量

c++ - Windows Phone 8 上的性病

c++ - 模板内的编辑列表不保存

c++ - __debugbreak 的可移植等效项

c++ - C++20 模板ambas 的限制和使用