C++: Inheriting from std::map

后端 未结 4 1845
无人及你
无人及你 2020-12-31 00:44

I want to inherit from std::map, but as far as I know std::map hasn\'t any virtual destructor.

Is it therefore possible to call std

4条回答
  •  没有蜡笔的小新
    2020-12-31 01:05

    I want to inherit from std::map [...]

    Why ?

    There are two traditional reasons to inherit:

    • to reuse its interface (and thus, methods coded against it)
    • to reuse its behavior

    The former makes no sense here as map does not have any virtual method so you cannot modify its behavior by inheriting; and the latter is a perversion of the use of inheritance which only complicates maintenance in the end.


    Without a clear idea of your intended usage (lack of context in your question), I will suppose that what you really want is to provide a map-like container, with some bonus operations. There are two ways to achieve this:

    • composition: you create a new object, which contains a std::map, and provide the adequate interface
    • extension: you create new free-functions that operate on std::map

    The latter is simpler, however it's also more open: the original interface of std::map is still wide-opened; therefore it is unsuitable for restricting operations.

    The former is more heavyweight, undoubtedly, but offers more possibilities.

    It's up to you to decide which of the two approaches is more suitable.

提交回复
热议问题