我很难理解以下两段代码为何有所不同,编译器到底在做什么。

我有以下一些琐碎的代码,可以按预期进行编译而没有任何问题:

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++编译器如何编译代码的模板版本,它与编译原始示例有何不同,这是代码多次传递以及类型依赖外观的问题吗? UPS?

最佳答案

在第二个版本中,booboo是从属名称,因此它不会在模板中自动显示。您可以将using typename base<T>::booboo;添加到派生类,或者使用typedef解决方案,或者说typename base<T>::booboo bb = T(1);

关于c++ - 从模板基类派生时找不到类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15236870/

10-11 22:48