在类中定义类型

Typedef in class

本文关键字:类型 定义      更新时间:2023-10-16

有这样的代码:

template <class T>
class SomeClass{
    typedef boost::shared_ptr<T> sPtr;
    typedef std::vector<sPtr> c;
    typedef c::iterator cIt;  // here is the problem
};

,错误是:

main.cpp:23: error: type ‘std::vector<boost::shared_ptr<X>, std::allocator<boost::shared_ptr<X> > >’ is not derived from type ‘SomeClass<T>’
main.cpp:23: error: expected ‘;’ before ‘cIt’

如何在类中使用typedef模板化参数?

编辑:

我算出来了,对于g++,它必须是:

typedef typename c::iterator cIt;  // here is the problem

问题是c::iterator限定id,而c的类型取决于模板参数。根据§14.6/3:

限定id打算引用一个不是当前实例化成员的类型,并且它的嵌套名称说明符引用一个依赖类型时,它应该是以关键字typename…作为前缀