我有以下问题,我想知道是否有更好的方法来解决它:
class myObj {
public:
typedef std::shared_ptr<myObj> handle;
typedef std::shared_ptr<const myObj> const_handle;
int someMethod() { ... }
int someConstMethod() const { ... }
};
现在我需要的是一个容器类,它允许您myObj
根据自己的需要修改或读取集合const
,如下所示:
class myCollection {
public:
typedef std::list<myObj::handle> objList;
typedef std::list<myObj::const_handle> const_objList;
inline objList& modify() { return _obl; }
// it would be nice to do this, but it won't compile as
// objList and const_objList are completely different types
inline const_objList& read() const { return _obl; } // doh! compile error...
// returning a const objList won't help either as it would return non-const
// handles, obviously.
// so I am forced to do this, which sucks as i have to create a new list and copy
void read(const_objList &l) {
std::for_each(
_obl.begin(),
_obl.end(),
[&l] (myObj::handle &h) { l.push_back(h); }
// ok as handle can be cast to const_handle
); // for_each
}
private:
objList _obl;
};
所以这个解决方案实际上const myCollection
只允许你获取一个列表,它只允许你调用(GOOD)const_handle
的非修改方法。myObj
问题是 " read
" 方法真的很丑 (BAD)。
另一种方法是以某种方式公开list
方法并根据需要返回const_handle
和处理,但这会产生很多开销,特别是如果您想使用比列表更复杂的东西。
任何想法?