2008-03-01
GCC不能正确继承模板类
GCC编译器似乎不能理解继承自模板类里的数据成员。我还以为是代码的问题,郁闷了半天后,居然在Borland C++ 5.5下编译通过了。节省篇幅,我抽出主要部分。
B类的id本应该是从A类里继承来的,但用GCC编译会提示说变量id未定义。试着用Borland的编译器就很痛快地过了。我使用的是MinGW的GCC 3.4,但我在Unix-Center的机器上使用Unix和Linux版本的GCC 4.0编译仍然通不过,但Solaris上的Sun Studio的C++编译器则没问题。
难道就这么幸运地碰上GCC的Bug了?
template<class T>
class A{
protected:
T id;
};
template<class T>
class B: public A<T>{
public:
void setid(T i){
id=i;
}
void test1(){
cout<<"B::test1() ID: "<<id<<endl;
}
};
B类的id本应该是从A类里继承来的,但用GCC编译会提示说变量id未定义。试着用Borland的编译器就很痛快地过了。我使用的是MinGW的GCC 3.4,但我在Unix-Center的机器上使用Unix和Linux版本的GCC 4.0编译仍然通不过,但Solaris上的Sun Studio的C++编译器则没问题。
难道就这么幸运地碰上GCC的Bug了?
- by ggggqqqqihc
- 浏览 (1413)
- 评论 (2)
- 相关推荐


评论
http://blog.olivierlanglois.net/index.php/2007/08/19/dependent_names_and_two_phase_lookup
GFW封了,我贴一部分出来:
If VC++ does not complain, it is because it simply does not support the two phase lookup and compile templates only at instantiation point. GCC is a better compiler in that aspect because it complies with the C++ standard by implementing the Two-Phase lookup. You can easily fool VC++ with the following code:
template <class T>
class Test
{
public:
void Test() { foo(); }
private:
T m_a;
}
// Non dependent function declared after
// template declaration
int foo();
int main(int argc, char *argv[])
{
Test<int> testObj;
testObj.Test();
return 0;
}
GCC will generate an error when encountering the template complaining that foo() is not declared but VC++ will happily accept this code. Now that this is explained, note that except annoyance when porting code from VC++ to GCC or any other standard compliant compiler, the only consequence for MSVC of not being totally C++ standard compliant by not supporting the Two-Phase lookup is that if there are errors in a template, the compiler will delay their report at its instantiation instead of reporting them as soon as the template is encountered.