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;
}
};