从模板基类派生时类型未找到(Type not found when derived from tem

2019-07-21 02:08发布

我难以理解为什么会出现在以下两个代码段,究竟是编译器做一个区别。

我的琐碎以下代码位,符合市场预期,没有任何问题,编译:

class base
{
public:
   typedef int booboo;
};

class derived : public base
{
public:
   int boo()
   {
      booboo bb = 1;
      return bb;
   }
};

int main()
{
   derived d;
   d.boo();
   return 0;
}

我把代码从上面添加一些模板参数,并开始获得与该类型BOOBOO不是有效的错误:

template <typename T>
class base
{
public:
   typedef T booboo;
};

template <typename T>
class derived : public base<T>
{
public:
   //typedef typename base<T>::booboo booboo; <-- fixes the problem
   booboo boo()
   {
      booboo bb = T(1);
      return bb;
   }
};

int main()
{
   derived<int> d;
   d.boo();
   return 0;
}

错误:

prog.cpp:13:4: error: ‘booboo’ does not name a type
prog.cpp:13:4: note: (perhaps ‘typename base<T>::booboo’ was intended)
prog.cpp: In function ‘int main()’:
prog.cpp:23:6: error: ‘class derived<int>’ has no member named ‘boo’

http://ideone.com/jGKYIC

我想在细节,典型的C ++编译器如何去有关编译的代码模板版本,它从编译原来的例子有什么不同理解,这是一个问题做了代码的多次通过和类型取决于look- UPS?

Answer 1:

在第二个版本, booboo是一个从属名称 ,所以它是不会自动在模板中可见。 你可以添加using typename base<T>::booboo; 派生类,或使用您的typedef溶液,或说typename base<T>::booboo bb = T(1);



文章来源: Type not found when derived from template base class