在 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) 通过将缓存对象中的迭代器保持在其在列表中的位置来加快回收。如果有人对如何实现这些有更好的想法(前提是无法修复此错误),我很想听听。
最佳答案
您的代码具有未定义的行为,因为您正在使用不完整的类型实例化 std::list
(Proxy
尚未在其定义中定义)。 [res.on.functions]/2
:
... the effects are undefined ... if an incomplete type is used as a template argument when instantiating a template component, unless specifically allowed for that component.
尝试使用 list
的实现 works with incomplete types ,例如 boost::container::list .
关于c++ - 模板类的内部类不会在 XCode 4.5.2 上编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15102111/