我可以做吗?
例如,考虑以下结构:
struct bag {
string fruit;
string book;
string money;
};
我想以顺序形式打印结构包实例的字段值并获得如下输出:
apple
Computer Networking, A top-down Approach
100
但不使用领域的名称(水果、书籍和金钱)。任何帮助,将不胜感激。我知道的唯一信息是所有字段都是 C++ 字符串。
虽然C++没有反射,但您可以使用以下命令制作自己的反射工具Boost.Hana http://boostorg.github.io/hana/。这是一个完整的程序,它迭代结构体的成员,打印它们的名称和值。
Hana 需要一个符合 C++14 标准的现代编译器,这意味着最新版本的 Clang 或 GCC 6+ 是您目前此代码的唯一选择。
编辑:此代码现在使用BOOST_HANA_ADAPT_STRUCT
代替BOOST_HANA_ADAPT_ADT
.
#include <boost/hana/adapt_struct.hpp>
#include <boost/hana/for_each.hpp>
#include <boost/hana/fuse.hpp>
#include <string>
#include <iostream>
namespace hana = boost::hana;
using std::string;
struct bag {
string fruit;
string book;
string money;
};
BOOST_HANA_ADAPT_STRUCT(bag, fruit, book, money);
int main() {
bag my_bag{ "Apple", "To Kill A Mockingbird", "100 doubloons" };
hana::for_each(my_bag, hana::fuse([](auto member, auto value) {
std::cout << hana::to<char const*>(member) << " = " << value << "\n";
}));
}
Output:
fruit = Apple
book = To Kill A Mockingbird
money = 100 doubloons
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)