模板类中的Typedef不起作用 [英] Typedef inside template class doesn't work
问题描述
我对以下代码有疑问:
template <typename U>
class lamePtr
{
public:
typedef U* ptr;
};
template <typename U>
class smarterPointer
{
public:
void funFun()
{
typedef lamePtr<U> someType;
someType::ptr query;
}
};
如您所见,我在lamePtr中有一个typedef.在smarterPointer类内部,我有一个函数funFun().我想做的是使另一个typedef someType.直到那一行,一切正常为止,直到我们通过someType :: ptr查询到达该行为止.
As you see, I have a typedef inside lamePtr. Inside smarterPointer class I have a function funFun(). What am I trying to do is to make another typedef someType. Till that line, everything works fine until we get to the line with someType::ptr query.
我想在这里发生的是查询"将变为lamePtr< U> :: ptr(一个简单值,不是typedef;).但是,出现编译错误(使用gcc 4.4.3):
What I want here to happen is that "query" will become lamePtr< U >::ptr (a simple value, not a typedef ;). However, I get compilation errors (with gcc 4.4.3):
temp.cpp: In member function ‘void smarterPointer<U>::funFun()’:
temp.cpp:15: error: expected ‘;’ before ‘query’
我在做什么错了?
推荐答案
someType
,因为lamePtr<U>
是从属名称".是否有成员ptr
取决于U
是什么,如果有,则取决于该成员是什么样的事物".
someType
, as lamePtr<U>
is a "dependant name". It depends on what U
is as to whether or not there is a member ptr
and, if so, what kind of "thing" that member is.
当然,您知道对于所有T
,lamePtr<T>::ptr
是一种类型,但是在编译的这一阶段,解析器并不知道这一点.
Of course, you know that for all T
, lamePtr<T>::ptr
is a type, but at this stage of compilation the parser does not know that.
使用 typename
关键字提示解析器一种.其余的将在以后的编译过程中解决.只是一点C ++怪癖.
Use the typename
keyword to hint to the parser that it's a type. The rest will be resolved later in the compilation process. Just a little C++ quirk.
template <typename U>
class lamePtr
{
public:
typedef U* ptr;
};
template <typename U>
class smarterPointer
{
public:
void funFun()
{
typedef lamePtr<U> someType;
typename someType::ptr query;
}
};
这篇关于模板类中的Typedef不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!