C ++ Template类继承具有模板指定输入类型的另一个模板类 [英] C++ Template class inheriting another template class with a template-specified input type
问题描述
可能重复:
GCC问题:使用依赖于模板参数的基类成员
为什么海湾合作委员会需要额外的声明在VS没有的模板中?
为什么没有’ ta派生的模板类可以访问基本模板类
iphone编译器继承模板化基类,传递类型未及时扩展(只看)
对于令人困惑的标题感到抱歉,我能想出最好的。
Sorry for the confusing title, best I could come up with.
这里是一些代码来说明我的问题...
Here's some code to illustrate my problem...
基本模板类:
template<class T> class TestBase
{
public:
int someInt;
};
尝试使用另一个模板类继承TestBase ...
这在编译时得到someInt未在此范围内声明:
This gets "someInt was not declared in this scope" at compile time:
template<class X> class TestSub : public TestBase<X>
{
void testf()
{
someInt = 0; //Error: "someInt was not declared in this scope"
}
};
B)
这样可行(不同之处在于我明确指定了TestBase的模板输入)
B)
This works fine (the difference being that I specify TestBase's template input explicitly)
template<class X> class TestSub : public TestBase<string>
{
void testf()
{
someInt = 0;
}
};
为什么(A)的TestSub不像(B)中那样正确地继承someInt?
Why does TestSub from (A) not inherit someInt correctly as it does in (B)?
提前致谢。
推荐答案
因为无论X最终存在什么,TestBase都可以专注于X.因此,您需要通过完全限定它来让编译知道someInt是一个依赖值。而不是
Because TestBase could be specialized on X whatever X ends up being. Therefore you need to let the compile know someInt is a dependent value by fully qualifying it. Instead of
someInt = 0
说而不是
TestBase<X>::someInt = 0
您还可以使用
this->someInt = 0
重点是编译器不会假设某个名称依赖于模板参数必须知道它是在它将检查推迟到实例化时间之前。对于实验,请参阅引入全局someInt时会发生什么。
The point is the compiler will not assume a name is dependent on a template parameter it must know it is before it defers that check to instantiation time. For an experiment see what happens when you introduce a global someInt.
这篇关于C ++ Template类继承具有模板指定输入类型的另一个模板类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!