c++ - 从用户定义的类生成格式字符串?
问题描述
是否有任何相对简单的模板元编程或类似的方法来获取如下结构:
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 中,您可以使用折叠表达式。
推荐阅读
- vba - VBA 刮板
- input - 如何获取用户的输入?
- c# - UWP 从后台任务中读取注册表并将信息反馈给 UI
- multithreading - OMP_PLACES was not declared in this scope
- javascript - 这是对打字稿的良好转换吗?为什么会出现这个错误?
- angular - 如何在Angular中使用ngModel在表格的每一行中绑定不同的输入文本值
- php - 循环遍历常规数组时,不能将 stdClass 类型的对象用作数组
- discord - 如何在不重新邀请的情况下在不和谐机器人中使用斜杠命令?
- android - 使用 lambda 的 Kotlin setOnClickListener 语法
- sql - 如何使用 SQL Query 获取前几年到上个月的数据?