【问题标题】:C++ Template class inheriting another template class with a template-specified input type [duplicate]C ++模板类继承另一个具有模板指定输入类型的模板类[重复]
【发布时间】:2011-03-17 17:00:49
【问题描述】:

可能的重复:
GCC problem : using a member of a base class that depends on a template argument
Why does GCC need extra declarations in templates when VS does not?
Why doesn’t a derived template class have access to a base template class
iphone compiler inherited templated base classes with passed through type not being expanded in time (just look)

抱歉标题混乱,我能想到的最好的。

这里有一些代码来说明我的问题...

一个基本模板类:

template<class T> class TestBase
{
public:
   int someInt;
};


正在尝试用另一个模板类继承 TestBase...

这会在编译时得到“someInt was not declared in this scope”:

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?

提前致谢。

【问题讨论】:

标签: c++ inheritance templates


【解决方案1】:

因为无论 X 最终是什么,TestBase 都可以专门用于 X。因此,您需要通过完全限定它来让编译知道 someInt 是一个依赖值。而不是

     someInt = 0

不如说

     TestBase<X>::someInt = 0

你也可以使用

     this->someInt = 0

关键是编译器不会假定名称依赖于模板参数,它必须在将检查推迟到实例化时间之前知道它是什么。对于一个实验,看看当你引入一个全局 someInt 时会发生什么。

【讨论】:

  • 或者使用this-&gt;someInt代替完全限定。
  • 请注意,将查找推迟到实例化是不够的。该标准明确指出,即使在实例化时,在非限定查找期间也不会在相关基类中查找非限定名称。它恰好适用于this-&gt;someInt 和其他人,因为它们不会进行不合格的查找。这个细节在推理时经常被忽略,但它很重要。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-02
  • 1970-01-01
  • 2020-06-26
  • 2012-10-05
  • 1970-01-01
相关资源
最近更新 更多