Joh*_*nck 4 c++ introspection boost-fusion
给定这样的结构:
struct Foo
{
int x;
int y;
double z;
};
BOOST_FUSION_ADAPT_STRUCT(Foo, x, y, z);
Run Code Online (Sandbox Code Playgroud)
我想生成一个这样的字符串:
"{ int x; int y; double z; }"
Run Code Online (Sandbox Code Playgroud)
我已经看到了如何打印 Fusion适应结构的值,但是在这里我只需要打印类型和名称。
我该如何简单地做到这一点?如果有更好的方法,我不嫁给Boost.Fusion。
我认为您可以通过对该答案中的代码进行一些稍微的修改来获得与您想要的类似的东西。您可以使用轻松获取成员名称,boost::fusion::extension::struct_member_name但据我所知,您无法直接获取成员类型名称。您可以使用boost::fusion::result_of::value_at(在其他选项中)获取成员类型,并且我选择使用Boost.TypeIndex来获取其名称(不同程度的修饰,具体取决于编译器和所讨论的类型)。所有这些都是假设您实际上需要Fusion适配,否则您可能会得到一种更简单的方法,该方法只能满足您的需要。
在WandBox(gcc)上运行的完整代码(
extend)(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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
713 次 |
| 最近记录: |