从用户定义的类生成格式字符串?

Generating a format string from a user defined class?

本文关键字:格式 字符串 用户 定义      更新时间:2023-10-16

模板元编程或类似的方法是否有任何相对简单的方法来获取这样的结构:

struct data { 
int32_t off;
int16_t len;
int8_t  bla;
};

并从中生成格式字符串?

类似format<data>() == "OFF/SL LEN/SI BLA/SB"

这不是我需要的实际格式,但简单的文本性质的东西会很好。

我认为不使用第三方库就没有简单的事情可以做到。 一种有效(但需要一些努力(的方法是为要转换的每种类型定义一个to_tuple函数。 例如:

auto to_tuple(data const& d)
{
return std::tie(d.off, d.len, d.bla);
}

然后,format函数可以对提供的参数调用to_tuple,并使用它来反映类型:

template <class... T> std::string format_impl(std::tuple<T...> const& obj)
{
// do something with the tuple members
}
template <class T> std::string format(T const& obj)
{
return format_impl(to_tuple(obj));
}

如果你真的被限制在C++11上,"做点什么"是很棘手的。 在 C++14 中,使用std::index_sequence相对容易。 在 C++17 中,您可以使用折叠表达式。