fmtlib / fmt

A modern formatting library
https://fmt.dev
Other
20.86k stars 2.51k forks source link

Extend the interface of join to pass nested separator down #4240

Closed correaa closed 1 week ago

correaa commented 1 week ago

With fmt, one can pass a range and a separator to fmt::join. I wonder if it is possible to extend the interface of join (or something with another name) to pass extra parameters that will be utilized internally, if other calls to std::join are made recursively.

So if a nested vector is passed: std::vector<std::vector<T>> is passed to fmt::join( vv, ",", "~") then the top level is separated by "," and the lower level is separated by "~".

(It is possible that it could be a hard error if join is not called internally, or alternative, that the subsequent argument is ignored if not used --more elegant--)

This will replace something like:

...
    constexpr auto join_sp = [](auto&& row) { return fmt::join(row, "~"); };
    fmt::print(
        "{}",
        fmt::join(
            std::views::transform(arr, join_sp),
            ", "
        )
    );

with this: fmt::print( "{}", fmt::join(arr, ", ", "~") ).

https://godbolt.org/z/nKcas4Ka4

See here: https://stackoverflow.com/questions/79193937/control-fmt-formatting-of-nested-containers-ranges/79194118#79194118

PS: I know this has a flaw that is that the enclosing opening and closing format is still not specified, that needs more though I guess.

Feel free to close this issue if you think that is out of the scope of the library.

vitaut commented 1 week ago

It's an interesting idea but it seems a bit niche. I think it belongs to a custom formatter rather than the {fmt} library.

correaa commented 1 week ago

Thank you for considering the idea. Now that there are so many "rank increasing" views, such as std::view::split, std::lazy_split, std::view::slide, std::views::chunk, std::views::chunk_by, it could be a nice way to print those out-of-the-box.

Consider, for example, printing std::vector{1, 2, 3, 4} | stdv::chunk(2).

vitaut commented 1 week ago

I think the default formatting is sufficient and if anything more fancy is desired it can be done through an adapter.