Pretty-print C++ STL containers

前端 未结 10 1734
谎友^
谎友^ 2020-11-21 07:39

Please take note of the updates at the end of this post.

Update: I have created a public project on GitHub for this library!


10条回答
  •  既然无缘
    2020-11-21 07:44

    I am going to add another answer here, because I have come up with a different approach to my previous one, and that is to use locale facets.

    The basics are here

    Essentially what you do is:

    1. Create a class that derives from std::locale::facet. The slight downside is that you will need a compilation unit somewhere to hold its id. Let's call it MyPrettyVectorPrinter. You'd probably give it a better name, and also create ones for pair and map.
    2. In your stream function, you check std::has_facet< MyPrettyVectorPrinter >
    3. If that returns true, extract it with std::use_facet< MyPrettyVectorPrinter >( os.getloc() )
    4. Your facet objects will have values for the delimiters and you can read them. If the facet isn't found, your print function (operator<<) provides default ones. Note you can do the same thing for reading a vector.

    I like this method because you can use a default print whilst still being able to use a custom override.

    The downsides are needing a library for your facet if used in multiple projects (so can't just be headers-only) and also the fact that you need to beware about the expense of creating a new locale object.

    I have written this as a new solution rather than modify my other one because I believe both approaches can be correct and you take your pick.

提交回复
热议问题