Typedef inside template class doesn't work

2019-04-06 19:50发布

问题:

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?

回答1:

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


回答2:

You need the typename keyword to signify that someType::ptr is a type.

    typename someType::ptr query;

See Officially, what is typename for? for detail.