Typedef inside template class

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 TlamePtr<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标记出这是类型,而不是成员变量

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值