最佳答案
我有一个类,它适应 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.
}