首页 > 解决方案 > 从用户定义的类生成格式字符串?

问题描述

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

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

并从中生成格式字符串?

就像是format<data>() == "OFF/SL LEN/SI BLA/SB"

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

标签: c++c++11

解决方案


我不认为没有使用第三方库可以做任何简单的事情。一种有效的方法(但需要一些努力)是为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 中,您可以使用折叠表达式。


推荐阅读