从模板基类派生时找不到类型 [英] Type not found when derived from template base class

查看:149
本文介绍了从模板基类派生时找不到类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having difficulty understanding why there is a difference in the following two pieces of code, what exactly is the compiler doing.

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

I have the following bit of trivial code, that compiles without any problems as expected:

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的错误:

I take the code from above and add some template parameters, and begin to get errors relating the type booboo not being valid:

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 ++编译器如何编译代码的模板版本,它与编译原始示例有何不同,这是与代码的多次传递有关的问题,并且键入依赖查找?

I would like to understand in details, how a typical c++ compiler goes about compiling the template version of the code, how it differs from compiling the original example, is this an issue to do with multiple passes of the code, and type dependent look-ups?

推荐答案

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

In the second version, booboo is a dependent name, so it is not automatically visible in the template. You can either add using typename base<T>::booboo; to the derived class, or use your typedef solution, or say typename base<T>::booboo bb = T(1);.

这篇关于从模板基类派生时找不到类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆