读书人

泛型编程模板类相关有关问题

发布时间: 2013-01-19 11:41:36 作者: rapoo

泛型编程,模板类相关问题
各位大侠,小弟重载一个容器类,想实现新增、删除一个对象后通知元素对象的需求。代码见下。碰到的问题是,如果插入的是对象,一切正常,插入的是对象指针,编译不通过。故求一有效解决办法……

Code:
class IElement
{
public:
virtual void __fastcall OnAdded() {}
virtual void __fastcall OnRemoved() {}
};

template <typename T1, class IElement>
class IContainer
: private std::map<T1, IElement>
{
public:
__fastcall IContainer() {}
__fastcall ~IContainer() { Clear(); }

bool __fastcall Add(const T1& key, const IElement& elem, bool bReplace = false)
{
bool bRet = false;

lock_.lock();

do
{
if( !bReplace )
{

std::map<T1, IElement>::iterator iter;
iter = std::map<T1, IElement>::find(key);
if(iter != std::map<T1, IElement>::end())
{
break;
}
}
bRet = true;

std::map<T1, IElement>::insert(std::make_pair(key, elem));
operator [](key).OnAdded(); //此处报错

}while(0);

lock_.unlock();

return bRet;
}

const IElement& operator [] (const T1& key)
{
lock_.lock();

try
{
std::map<T1, IElement>::iterator iter;
iter = std::map<T1, IElement>::find(key);
if(iter == std::map<T1, IElement>::end())
{
throw Exception("can not found the Key");
}


}
__finally
{
lock_.unlock();
}

return (std::map<T1, IElement>::operator [](key));
}

private:
ILock lock_;
};

现在 IContainer<int, IElement> Elems;IContainer<int, IElement*> pElems;
都能通过编译,但是Add IElement*类型时,报错。
Error Info: E2294 Structure required on left side of . or .*
[解决办法]
类中定义


template<class Element> struct TypePointer
{
enum{ value = 0};
};

template<class Element> struct TypePointer<Element*>
{
enum{ value = 1};
};

enum { IsPointer = TypePointer<IElement>::value };


template<bool> void OnAddedNotify(const IElement& Ele)
{
Ele.OnAdded();
}

template<> void OnAddedNotify<true>(const IElement& Ele)
{
Ele->OnAdded();
}


调用 OnAdded 的时候 用OnAddedNotify代替

OnAddedNotify<IsPointer>(elem);


另外 map中的 元素 是const的,OnAdded函数也改为const的

读书人网 >C++ Builder

热点推荐