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