http://stackoverflow.com/questions/5524744/typedef-inside-template-class-doesnt-work
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?
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.
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.
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;
}
};
总结就是:
在父类中有一个类型叫ptr, 但是对于子类而言,如果用lamePtr<U>::ptr的形式,不能判断是静态成员变量还是类型,所以要用typename标记出这是类型,而不是成员变量
解释了在模板类内部使用typedef导致的问题,并提供了解决方法。
1826

被折叠的 条评论
为什么被折叠?



