模板类中的 Typedef 不起作用
我对以下代码有疑问:
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 查询的行。
我希望发生的是“query”将变成 lamePtr< U >::ptr (一个简单值,不是 typedef ;)。但是,我收到编译错误(使用 gcc 4.4.3):
temp.cpp: In member function ‘void smarterPointer<U>::funFun()’:
temp.cpp:15: error: expected ‘;’ before ‘query’
我在这里做错了什么?
I have a problem with the following code:
template <typename U>
class lamePtr
{
public:
typedef U* ptr;
};
template <typename U>
class smarterPointer
{
public:
void funFun()
{
typedef lamePtr<U> someType;
someType::ptr query;
}
};
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.
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’
What am I doing wrong here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
someType
,因为lamePtr
是“从属名称”。这取决于U
是否存在成员ptr
,以及如果存在,该成员是什么类型的“事物”。当然,你知道对于所有
T
,lamePtr::ptr
都是一种类型,但在编译的这个阶段,解析器不知道。使用
typename
关键字 提示解析器它是一种类型。其余的将在稍后的编译过程中解决。只是一点 C++ 的怪癖。someType
, aslamePtr<U>
is a "dependant name". It depends on whatU
is as to whether or not there is a memberptr
and, if so, what kind of "thing" that member is.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.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.您需要
typename
关键字来表示someType::ptr
是一种类型。有关详细信息,请参阅官方,typename 的用途是什么?。
You need the
typename
keyword to signify thatsomeType::ptr
is a type.See Officially, what is typename for? for detail.