问题描述
给出这样的结构:
struct Foo
{
int x;
int y;
double z;
};
BOOST_FUSION_ADAPT_STRUCT(Foo, x, y, z);
我想生成一个这样的字符串:
I want to generate a string like this:
"{ int x; int y; double z; }"
我已经看到了如何打印Fusion适应结构的值 ,但是这里我只需要打印类型和名称.
I have seen how to print the values of a Fusion adapted struct, but here I need to print the types and names only.
我该如何简单地做到这一点?如果有更好的方法,我还没有嫁给Boost.Fusion.
How can I do this mostly simply? I'm not married to Boost.Fusion if there's a better way.
推荐答案
我认为您可以通过对.您可以使用boost::fusion::extension::struct_member_name
轻松获取成员名称,但是据我所知,您无法直接获取成员类型名称.您可以使用boost::fusion::result_of::value_at
(在其他选项中)来获取成员类型,而我选择使用Boost.TypeIndex来获取其名称(不同程度的修饰,具体取决于编译器和所讨论的类型).所有这些都是假设您确实需要Fusion适配,否则您可能会得到一种更简单的方法,该方法只能满足您的需要.
I think you can get something similar to what you want by making some slight modifications on the code in this answer. You can easily get the member name using boost::fusion::extension::struct_member_name
but, as far as I know, you can't directly get the member type name. You can get the member type using boost::fusion::result_of::value_at
(amongst other options) and I've chosen to use Boost.TypeIndex to get its name (in varying degrees of prettiness, depending on the compiler and the types in question). All of this is assuming that you actually need the Fusion adaptation, if you don't you can probably get a simpler approach that does only what you need.
完整代码
在WandBox(gcc)上运行
在rextester(vc)上运行
Full Code
Running on WandBox (gcc)
Running on rextester (vc)
#include <iostream>
#include <string>
#include <boost/mpl/range_c.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/include/zip.hpp>
#include <boost/fusion/include/at_c.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/mpl.hpp>
#include <boost/type_index.hpp>
namespace fusion=boost::fusion;
namespace mpl=boost::mpl;
struct Foo
{
int x;
int y;
double z;
};
BOOST_FUSION_ADAPT_STRUCT(Foo, x, y, z);
struct Bar
{
std::pair<int,int> p;
std::string s;
};
BOOST_FUSION_ADAPT_STRUCT(Bar, p, s);
template <typename Sequence>
struct Struct_member_printer
{
Struct_member_printer(const Sequence& seq):seq_(seq){}
const Sequence& seq_;
template <typename Index>
void operator() (Index) const
{
std::string member_type = boost::typeindex::type_id<typename fusion::result_of::value_at<Sequence,Index>::type >().pretty_name() ;
std::string member_name = fusion::extension::struct_member_name<Sequence,Index::value>::call();
std::cout << member_type << " " << member_name << "; ";
}
};
template<typename Sequence>
void print_struct(Sequence const& v)
{
typedef mpl::range_c<unsigned, 0, fusion::result_of::size<Sequence>::value > Indices;
std::cout << "{ ";
fusion::for_each(Indices(), Struct_member_printer<Sequence>(v));
std::cout << "}\n";
}
int main()
{
Foo foo;
print_struct(foo);
Bar bar;
print_struct(bar);
}
这篇关于Boost Fusion:将适应的结构类型转换为文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!