gpt4 book ai didi

c++ - boost 结构和类的 fusion 序列类型和名称识别

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:18:48 25 4
gpt4 key购买 nike

我正在尝试为我的一个项目使用 boost fusion,并且我正在弄清楚如何获取结构和类的类型名称和变量名称。

#include <typeinfo>
#include <string>
#include <iostream>
#include <boost/fusion/include/sequence.hpp>
#include <boost/fusion/include/algorithm.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/fusion/include/adapt_adt.hpp>

#include <boost/lexical_cast.hpp>

using namespace boost::fusion;

struct Foo
{
int integer_value;
bool boolean_value;
};


class Bar
{
int integer_value;
bool boolean_value;
public:
Bar(int i_val, bool b_val):integer_value(i_val),boolean_value(b_val) {}
int get_integer_value() const { return integer_value; }
void set_integer_value(int i_val) { integer_value = i_val; }
bool get_boolean_value() const { return boolean_value; }
void set_boolean_value(bool b_val) { boolean_value = b_val; }
};

BOOST_FUSION_ADAPT_STRUCT(
Foo,
(int, integer_value)
(bool, boolean_value)
)

BOOST_FUSION_ADAPT_ADT(
Bar,
(int, int, obj.get_integer_value() , obj.set_integer_value(val))
(bool, bool, obj.get_boolean_value(), obj.set_boolean_value(val))
)


struct DisplayMembers
{

template <typename T>
void operator()(T& t) const {
std::cout << typeid(t).name() << " : " << boost::lexical_cast<std::string>(t) << std::endl;
}

};

int main(int argc, char *argv[])
{
struct Foo f = { 33, false};
for_each(f, DisplayMembers());

Bar b(34,true);
for_each(b, DisplayMembers());
return 0;
}

在上面的例子中结果是

int : 33
bool : 0
struct boost::fusion::extension::adt_attribute_proxy<class Bar,0,0> : 34
struct boost::fusion::extension::adt_attribute_proxy<class Bar,1,0> : 1

我想要的结果是

int : integer_value : 33
bool : boolean_value : 0
int : integer_value : 34
bool : boolean_value : 1

最佳答案

如果您使用的是 C++14,我将 sehe 的答案提炼成了更简单的东西

#include <iostream>

#include <boost/fusion/include/algorithm.hpp>
#include <boost/fusion/adapted/struct/adapt_struct.hpp>
#include <boost/fusion/include/adapt_struct.hpp>
#include <boost/mpl/range_c.hpp>

struct MyStruct {
std::string foo;
double bar;
};

BOOST_FUSION_ADAPT_STRUCT(MyStruct,
foo,
bar)

namespace fuz = boost::fusion;
namespace mpl = boost::mpl;

int main(int argc, char* argv[]) {
MyStruct dummy{"yo",3.14};

fuz::for_each(mpl::range_c<
unsigned, 0, fuz::result_of::size<MyStruct>::value>(),
[&](auto index){
std::cout << "Name: "
<< fuz::extension::struct_member_name<MyStruct,index>::call()
<< " Value: "
<< fuz::at_c<index>(dummy) << std::endl;
});

}

输出:

Name: foo Value: yo
Name: bar Value: 3.14

查看live on coliru

关于c++ - boost 结构和类的 fusion 序列类型和名称识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26380420/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com