我很难理解为什么以下两段代码存在差异,编译器到底在做什么。
我有以下一些琐碎的代码,可以按预期编译没有任何问题:
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’
.
我想详细了解,典型的 c++ 编译器如何编译代码的模板版本,它与编译原始示例有何不同,这是与代码的多次传递有关的问题,以及类型相关的外观 - UPS?