Inheriting classes from std::

后端 未结 3 478
南方客
南方客 2020-12-22 05:50

There are many similar questions and I found both pro and against reasons to use this pattern so I am asking this here:

I need to make a JSON implementation in C++ (

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-22 06:13

    It seems you're thinking that a JSON object is an unordered map, so it should inherit from std::unordered_map. I think you're making a logical jump here. A JSON object is definitely what you would describe as an example of an "unordered map", but is it really a std::unordered_map? I wouldn't say so. To say it's an std::unordered_map suggests that it should share the interface of std::unordered_map and should be able to be used anywhere that a std::unordered_map is used. I suggest that the interface of std::unordered_map is more complex and lower level than you'd want from a JSON object.

    On top of this, for the most part the standard library classes are not designed to be used as base classes (especially not if they're then used polymorphically).

    Considering these two points, I'd suggest that it makes much more sense for you to represent your JSON classes in terms of the standard library components, but not with an is-a relationship. Instead, use the standard library components as members of the JSON classes.

提交回复
热议问题