从用户定义的类生成格式字符串?
Generating a format string from a user defined class?
模板元编程或类似的方法是否有任何相对简单的方法来获取这样的结构:
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 中,您可以使用折叠表达式。
相关文章:
- 是否可以从格式字符串中检索"width"
- 我应该如何从 stdin C++ 中读取可变长度的格式字符串?
- 从用户定义的类生成格式字符串?
- 如何连接格式字符串?
- 如何在C++中将"%Y%m%d"格式字符串转换为time_t变量?
- CPPCHECK C++成员函数上的格式字符串
- scanf() 语句中"%*[^n]"的格式字符串指示什么?分配抑制器 (*) 和否定扫描集 ([^) 如何协同工作?
- 自定义 {fmt} 格式化函数,具有编译时格式字符串检查功能
- '|' scanf 格式字符串是什么意思
- 如何使用 msgfmt 验证格式字符串中的位置表示法占位符
- sscanf_s:格式字符串"%d"需要类型为"int *"的参数,但可变参数 4 的类型为"WORD *"
- C4477: 'fprintf' :格式字符串 '%s' 需要类型为"char *"的参数,但可变参数 1 的类型为"int *"
- 如何使用OpenSSL API从其PEM格式字符串中读取RSA公钥
- C 格式字符串宏
- C++等效于 C 的格式字符串
- 如何使用 C++ 中的 rapidjson 库从 json 格式字符串中获取值
- _vsnprintf和_vsnprintf_s的格式字符串中的可用百分比字符
- 如何将格式字符串发送到iostream
- 跨平台格式字符串
- 使用 swprintf() 打印"0x0"的格式字符串应该是什么?