從STL容器繼承實現而不是委托可以嗎?我有一個類來適應std:vectory來建模特定于域的對象的容器。我希望向用戶公開大部分STD:VectorAPI,以便他/她可以使用熟悉的方法(大小、清除、at等)。以及容器上的標準算法。在我的設計中,這似乎是一種反復出現的模式:class MyContainer : public std::vector<MyObject>{public:
// Redeclare all container traits: value_type, iterator, etc...
// Domain-specific constructors
// (more useful to the user than std::vector ones...)
// Add a few domain-specific helper methods...
// Perhaps modify or hide a few methods (domain-related)};我知道在為實現重用類時更喜歡組合而不是繼承的做法-但是一定會有限制的!如果我將所有內容委托給std:vectoral,那么就會有32個轉發函數!所以我的問題是.。在這種情況下繼承實現真的那么糟糕嗎?風險有多大?有沒有更安全的方法,我可以實現這一點,而不需要這么多的打字?我是一個使用實現繼承的異端者嗎?:)編輯:如何明確說明用戶不應通過std:Vectoral<>指針使用MyContainer:// non_api_header_file.hnamespace detail{
typedef std::vector<MyObject> MyObjectBase;}// api_header_file.hclass MyContainer : public detail::MyObjectBase{
// ...};Boost庫似乎一直在做這件事。編輯2:其中一項建議是使用免費功能。我將在這里顯示為偽代碼:typedef std::vector<MyObject> MyCollection;void specialCollectionInitializer(MyCollection& c, arguments...);result specialCollectionFunction(const MyCollection& c);etc...一種更OO的方法:typedef std::vector<MyObject> MyCollection;class MyCollectionWrapper{public:
// Constructor
MyCollectionWrapper(arguments...) {construct coll_}
// Access collection directly
MyCollection& collection() {return coll_;}
const MyCollection& collection() const {return coll_;}
// Special domain-related methods
result mySpecialMethod(arguments...);private:
MyCollection coll_;
// Other domain-specific member variables used
// in conjunction with the c
3 回答

慕斯王
TA貢獻1864條經驗 獲得超2個贊
template <typename Container>class readonly_container_facade {public: typedef typename Container::size_type size_type; typedef typename Container::const_iterator const_iterator; virtual ~readonly_container_facade() {} inline bool empty() const { return container.empty(); } inline const_iterator begin() const { return container.begin(); } inline const_iterator end() const { return container.end(); } inline size_type size() const { return container.size(); }protected: // hide to force inherited usage only readonly_container_facade() {}protected: // hide assignment by default readonly_container_facade(readonly_container_facade const& other): : container(other.container) {} readonly_container_facade& operator=(readonly_container_facade& other) { container = other.container; return *this; }protected: Container container;};template <typename Container>class writable_container_facade: public readable_container_facade<Container> {public: typedef typename Container::iterator iterator; writable_container_facade(writable_container_facade& other) readonly_container_facade(other) {} virtual ~writable_container_facade() {} inline iterator begin() { return container.begin(); } inline iterator end() { return container.end(); } writable_container_facade& operator=(writable_container_facade& other) { readable_container_facade<Container>::operator=(other); return *this; }};
- 3 回答
- 0 關注
- 616 瀏覽
添加回答
舉報
0/150
提交
取消