我正试图使用fmt::join
为std::unordered_map<std::string, Foo>
创建libfmt
formatter
,但似乎无法使其工作:
#include <fmt/core.h>
#include <fmt/format.h>
#include <unordered_map>
struct Foo{
int a;
};
using FooPair = std::pair<std::string, Foo>;
using FooMap = std::unordered_map<std::string, Foo>;
namespace fmt{
template <>
struct formatter<Foo> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const Foo& f, FormatContext& ctx) {
return format_to(ctx.out(), "n {}", f.a);
}
};
template <>
struct formatter<FooPair> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const FooPair& fp, FormatContext& ctx) {
return format_to(ctx.out(), "n {}{}", fp.first, fp.second);
}
};
template <>
struct formatter<FooMap> {
template <typename ParseContext>
constexpr auto parse(ParseContext& ctx) {
return ctx.begin();
}
template <typename FormatContext>
auto format(const FooMap& fm, FormatContext& ctx) {
return format_to(ctx.out(), "{}", fmt::join(fm.begin(), fm.end(), ""));
}
};
}
int main(){
FooMap foomap;
fmt::print("Foo Map: {}", foomap);
}
看起来我缺少了迭代器的格式化程序,但我尝试定义它以及const_iterator
的格式化程序都没有用。此处的最小示例:https://godbolt.org/z/q4615csG6
我确信我只是遗漏了一些愚蠢的东西,我只是现在看不见。
这里是固定版本:
https://godbolt.org/z/r6dGfzesz
using FooMap = std::unordered_map<std::string, Foo>;
using FooPair = FooMap::value_type;
问题是:using FooPair = std::pair<std::string, Foo>;
。注意unordered_map
的文档:
std::unordered_map-cppreference.com
value_type
标准::对<const键,T>
所以问题是不匹配类型:一对包含密钥(first
(的const
,另一对不包含。
所以另一种解决方法:
using FooPair = std::pair<const std::string, Foo>;
https://godbolt.org/z/9KT9j6h1b