我有一个类,它适应std :: vector来模拟特定于域的对象的容器.我想向用户公开大多数std :: vector API,以便他/她可以在容器上使用熟悉的方法(大小,清晰,等等......)和标准算法.在我的设计中,这似乎是一种反复出现的模式:
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)
};
Run Code Online (Sandbox Code Playgroud)
我知道在重用类实现时更喜欢使用组合继承的做法 - 但是必须有限制!如果我将所有内容委托给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
{
// ... …Run Code Online (Sandbox Code Playgroud)