도메인 별 개체의 컨테이너를 모델링하기 위해 std :: vector를 적용하는 클래스가 있습니다. 대부분의 std :: vector API를 사용자에게 노출하여 컨테이너에서 익숙한 메서드 (size, clear, 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 :: vector에 위임한다면, 32 개의 포워딩 함수가있을 것입니다!
그래서 내 질문은 ... 그런 경우에 구현을 상속하는 것이 정말 나쁜가요? 위험은 무엇입니까? 너무 많은 타이핑없이 이것을 구현할 수있는 더 안전한 방법이 있습니까? 구현 상속을 사용하는 이단자입니까? :)
편집하다:
사용자가 std :: vector <> 포인터를 통해 MyContainer를 사용해서는 안된다는 점을 명확히하는 것은 어떻습니까?
// non_api_header_file.h
namespace detail
{
typedef std::vector<MyObject> MyObjectBase;
}
// api_header_file.h
class MyContainer : public detail::MyObjectBase
{
// ...
};
부스트 라이브러리는 항상 이런 일을하는 것 같습니다.
편집 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 collection.
}