我正在编写一个程序来管理树和节点(DAG)。
节点用 表示class MCModule
。
class MCModule
{
...
};
typedef boost::shared_ptr<MCModule> MCModule_sp;
typedef MCModule * MCModule_p;
我有不同种类的容器。
例如,在我的 Node 类中,子节点使用共享指针进行管理。
std::list<shared_ptr<Node>> childs;
父节点在原始指针中进行管理:
std::list<Node *> parents;
不过,我也可能在另一个类中有一个节点指针向量。
所有这些容器都将类 Module 的“指针”存储在 shared_ptr 或原始指针中。
无论容器的类型是什么,我都需要执行一些相同的任务:根据名称、id、id 搜索节点
我开始编写以下模板类:
template<typename _ListT, typename _ElemT>
class ModuleListWrapper
{
public:
explicit ModuleListWrapper(_ListT& lst)
: m_lst(lst){}
/*! Indicates whether the \a module was found in the list or not
* \return true if the \a module was found, otherwise return false
*/
inline bool find(const MCModule_sp& module) {
return (std::find_if(m_lst.begin(),
m_lst.end(),
compare_with(module->getName()) ) != m_lst.end() );
}
inline _ElemT find(const std::string& name) {
_ListT::iterator it = std::find_if(m_lst.begin(), m_lst.end(), compare_with(name));
return ( it != m_lst.end() ) ? (*it) : NullPtrT;
}
// ... much more accessors ...
/*! Overloads the -> operator to facilitate the access to the inner class.
\return a pointer to the inner \a _ListT object
*/
inline _ListT * operator->() const { return &m_lst; }
/*! Gets a reference to the inner \a _ListT object
*/
inline _ListT& get() const { return m_lst; }
private:
_ListT& m_lst;
};
typedef ModuleListWrapper<ModuleList_shareptr, Module_shareptr> ModuleListWrapper_shareptr;
typedef ModuleListWrapper<ModuleList_rawptr, Module_p> ModuleListWrapper_rawptr;
typedef ModuleListWrapper<ModuleVector_rawptr, Module_p> ModuleListWrapper_rawptr;
此类的目的是提供一个接口来执行任何底层容器的操作。当然,容器必须“包含”预期类型的指针。
您认为这是一个可以接受的解决方案还是完全没用?当然它并不完美,但可能比从 std::list 或 std::vector 继承更好...?
欢迎任何批评、意见和建议。