gpt4 book ai didi

c++ - 在C++ {fmt}中格式化琐碎结构的扩展计划?

转载 作者:行者123 更新时间:2023-12-02 10:13:33 25 4
gpt4 key购买 nike

在我当前的项目中,我需要几个简单的数据传输对象(DTO)结构的自定义非常简单的“序列化”表示形式。在首次提出定制解决方案(这是一个很大的PITA)之后,我想到了使用{fmt}的想法。
所以最后几天,我通过fmt::formatter模板专门化机制的扩展来研究自定义类型的格式化。因此,this blogyour docs很有帮助。
经过一番摆弄之后,我想出了一个非常通用的poc解决方案,该解决方案允许以多种自定义格式格式化结构,看起来有点像以下内容:

struct Inner {
double x;
std::string y;
int z;
};
struct Outer {
int a;
std::string b;
Inner inner;
};

template<>
struct reflection<Outer> {
/*definition of class name and field names has to be provided manually...*/
};

template<>
struct reflection<Inner> {
/*definition of class name and field names has to provided manually...*/
};

/*
...
couple dozend lines of meta programming and fmt::formatter specializations.
...
*/

auto outer = Outer{.a=1,.b="hello",.inner={.x=3.12,.y=" ",.z=2}};

std::string simple = fmt::format("{:s}", outer); // :s means format as simple
assert(simple == "a|hello|3.12| |2");
assert(fmt::format("{:s;}", outer) == "a;hello;3.12; ;2");

std::string extended = fmt::format("{:e}",outer); // :e means format as extended
assert(extended == "Outer{.a=1, .b=hello, .inner=Inner{.x=3.12, .y= , .z=2}}");
显然,没有标准的方法可以反射(reflect)字段和结构的名称,因此必须手动或例如通过反射来提供反射结构。通过宏魔术。但这是一个不同的主题,我不想在这里解决。 -如果幸运的话,我们可以在c++ 23 \ o /中获得最小的编译时反射。让我们希望!
我将所有这些放到 this repo中。
实际问题:
通过{fmt}提供的简单反射API格式化用户定义的类型是否会成为您将来可能会扩展到{fmt}的方式?
我想象一个场景,其中预定义了一些简单的格式化模式,而用户只需要提供其类型的反射即可。
这样,我什至可以看到像 fmt::format("{:json,prety,tabwith=4}", outer)这样的格式化表达式。
另外,也许我只是在重新发明轮子,所以如果有类似的事情,基于{fmt}-告诉我! :)
无论如何,感谢您为社区提供了出色的工具,并恭喜您将其纳入c++ 20!
问候,马丁

最佳答案

Would formatting user defined types via a simple reflection API provided by {fmt} be something that you'd consider a possible future extension to {fmt}?


可能但可能必须是明确的选择加入,即此类类型不会以这种方式自动格式化,因为通常情况下,您希望使用更高级的表示形式而不是字段的集合。例如,您可能需要将点格式设置为 (x, y)而不是 Point{.x=x, .y=y}

关于c++ - 在C++ {fmt}中格式化琐碎结构的扩展计划?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62679099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com