VC++ 允許省略,GCC 強制要求。
// 錯誤 (GCC)
template class Foo { typedef T::SomeType SomeType; };
// 正確
template class Foo { typedef typename T::SomeType SomeType; };
// 迭代器宣告同理
template
void visit(const Container& c) {
for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) // typename 必加
...
}
VC++ 隱性查找基類模板參數相關成員,GCC 不查找。
template
class Derived : public Base {
public:
void foo() {
Base::base_func(); // 方法 1: 明確作用域
Base::m_member = 0;
}
};
// 或 using 引入 (適合大量使用)
template
class Derived : public Base {
using Base::base_func;
using Base::m_member;
public:
void foo() { base_func(); m_member = 0; }
};
VC++ 延遲編譯模板函數本體,允許前向宣告類別的成員存取與實例化;GCC 即時編譯,禁止。
// VC++ 通過,GCC 錯誤
class Forward;
template class Wrapper {
void use(Forward& f) { f.method(); } // Forward 未定義
void create() { Forward f; f.method(); }
};
class Forward { public: void method() {} };
class Forward; // 前向宣告
template class Wrapper {
public:
void use(Forward& f);
void create();
};
class Forward { public: void method() {} }; // 完整定義
// 定義移至此處,Forward 已完整
template inline void Wrapper::use(Forward& f) { f.method(); }
template inline void Wrapper::create() { Forward f; f.method(); }
T::Type → typename T::TypeBase::member 或 using Base::member本文源自將 ATL/WTL/WinX 移植至 MinGW-GCC 過程中遇到的真實問題,適用於任何 VC++ → GCC/Clang 跨平台移植專案。