可能的重复:
GCC 问题:使用依赖于模板参数的基类成员 https://stackoverflow.com/questions/11405/gcc-problem-using-a-member-of-a-base-class-that-depends-on-a-template-argument
为什么 GCC 需要在模板中额外声明,而 VS 不需要? https://stackoverflow.com/questions/2812470/why-does-gcc-need-extra-declarations-in-templates-when-vs-does-not
为什么派生模板类无法访问基模板类 https://stackoverflow.com/questions/1239908/why-doesnt-a-derived-template-class-have-access-to-a-base-template-class
iPhone编译器继承了模板化基类,传递的类型没有及时扩展(看看) https://stackoverflow.com/questions/2369553/iphone-compiler-inherited-templated-base-classes-with-passed-through-type-not-bei
抱歉,标题令人困惑,这是我能想到的最好的。
这是一些代码来说明我的问题......
基本模板类:
template<class T> class TestBase
{
public:
int someInt;
};
尝试使用另一个模板类对 TestBase 进行子类化...
这在编译时得到“someInt 未在此范围内声明”:
template<class X> class TestSub : public TestBase<X>
{
void testf()
{
someInt = 0; //Error: "someInt was not declared in this scope"
}
};
二)
这工作正常(区别在于我显式指定 TestBase 的模板输入)
template<class X> class TestSub : public TestBase<string>
{
void testf()
{
someInt = 0;
}
};
为什么 (A) 中的 TestSub 不像 (B) 中那样正确继承 someInt?
提前致谢。
因为 TestBase 可以专门针对 X,无论 X 最终是什么。因此,您需要通过完全限定 someInt 来让编译知道它是一个依赖值。代替
someInt = 0
而是说
TestBase<X>::someInt = 0
你也可以使用
this->someInt = 0
要点是编译器不会假设名称依赖于模板参数,它必须在推迟检查到实例化时间之前知道它。作为实验,看看引入全局 someInt 时会发生什么。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)