给定一个像这样的结构:
struct Foo
{
int x;
int y;
double z;
};
BOOST_FUSION_ADAPT_STRUCT(Foo, x, y, z);
我想生成一个像这样的字符串:
"{ int x; int y; double z; }"
我已经看到如何打印values https://stackoverflow.com/a/17660354/4323Fusion 改编的结构,但在这里我只需要打印类型和名称。
我怎样才能简单地做到这一点?如果有更好的方法的话,我不会选择 Boost.Fusion。
我认为你可以通过对代码进行一些轻微的修改来得到与你想要的类似的东西这个答案 https://stackoverflow.com/a/17842958/2417774。您可以使用以下方式轻松获取会员名称boost::fusion::extension::struct_member_name
但是,据我所知,您无法直接获取成员类型名称。您可以使用以下方式获取成员类型boost::fusion::result_of::value_at
(以及其他选项),我选择使用 Boost.TypeIndex 来获取其名称(不同程度的美观,具体取决于编译器和相关类型)。所有这些都是假设您实际上需要 Fusion 改编,如果您不需要,您可能会得到一种更简单的方法,只做您需要的事情。
完整代码
在 WandBox (gcc) 上运行 http://melpon.org/wandbox/permlink/garJmgbRY9Do9I9j
在 rextester (vc) 上运行 http://rextester.com/PQL69470
#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);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)