【发布时间】:2013-02-27 00:33:39
【问题描述】:
在 XCode 4.5.2 中,下面定义的类 Proxy 无法编译。如有必要,我可以提供有关特定编译器的更多详细信息,尽管它应该是默认值,因为我没有更改 XCode 配置中的任何内容。它在 VStudio Express 中编译。
#include <list>
#include <boost/thread/tss.hpp>
template <typename T>
class Cache
{
public:
class Proxy : public T
{
friend class Cache;
private:
std::list<Proxy> & m_refList;
typename std::list<Proxy>::iterator m_clsPosition;
Proxy(std::list<Proxy> & refList) : m_refList(refList) {}
};
private:
std::list<Proxy> m_clsList;
typename std::list<Proxy>::iterator m_clsCurrent;
static void Release(Proxy * ptrProxy)
{
ptrProxy->m_refList.splice(ptrProxy->m_refList.m_clsCurrent,
ptrProxy->m_refList,
ptrProxy->m_clsPosition);
if ( ptrProxy->m_refList.m_clsCurrent == ptrProxy->m_refList.end() )
--(ptrProxy->m_refList.m_clsCurrent);
}
public:
Cache() {m_clsCurrent = m_clsList.end();}
~Cache()
{
if ( m_clsList.size() && m_clsCurrent != m_clsList.begin() )
{
// ERROR - Cache not empty
}
}
typedef boost::shared_ptr<Proxy> Ptr;
static Ptr Get()
{
static boost::thread_specific_ptr<Cache> clsCache;
if ( clsCache.get() == NULL )
clsCache.reset(new Cache());
Proxy * ptrProxy;
if ( clsCache->m_clsCurrent == clsCache->m_clsList.end() )
{
clsCache->m_clsList.push_front(Proxy(clsCache->m_clsList));
ptrProxy = &(clsCache->m_clsList.front());
ptrProxy->m_clsPosition = clsCache->m_clsList.begin();
}
else
{
ptrProxy = &(*(clsCache->m_clsCurrent));
ptrProxy->m_clsPosition = clsCache->m_clsCurrent++;
}
return Ptr(ptrProxy, Release);
}
};
编译错误就在typename std::list<Proxy>::iterator m_clsPosition这一行:
No type named 'iterator' in 'std::__1::list<ASW::Cache<std::__1::basic_string<char>>::Proxy, std::__1::allocator<ASW::Cache<std::__1::basic_string<char>>::Proxy>>'
(Cache的模板参数为std::basic_string<char>)
我了解发生了什么 - 我在完全定义之前引用了 Proxy。但是为什么iterator需要Proxy的定义才能编译呢?
数据结构的原因有两个:1)回收对象而不是销毁它们,2)通过将缓存对象中的迭代器保持在列表中的位置来加速回收。如果有人对如何实现这些有更好的想法(假设无法修复此错误),我很想听听。
【问题讨论】:
-
从其他 cmets 可以看出,这是由于标准的限制。我简要地研究了
boost::container::list,这本来是可行的,因为它被设计为包含不完整的类型;我还查看了boost::ptr_list,但运行时不是 O(1) 用于移动列表中的节点。我最终滚动了自己的,我讨厌为这样的常见任务做这件事。测试完代码我会贴出来的。
标签: c++ xcode templates stl iterator