在 C++ 中不使用字段名称打印实例化结构的值

Ren*_*eza 2 c++ string struct

我可以做吗?

例如,考虑以下结构:

struct bag {
     string fruit;
     string book;
     string money;
};
Run Code Online (Sandbox Code Playgroud)

我想以顺序形式打印结构包实例的字段值并获得如下输出:

apple
Computer Networking, A top-down Approach
100
Run Code Online (Sandbox Code Playgroud)

但不使用领域的名称(水果、书籍和金钱)。任何帮助,将不胜感激。我知道的唯一信息是所有字段都是 C++ 字符串。

Bar*_*air 5

虽然C++没有反射,但您可以使用Boost.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";
    }));
}
Run Code Online (Sandbox Code Playgroud)

输出:

fruit = Apple
book = To Kill A Mockingbird
money = 100 doubloons
Run Code Online (Sandbox Code Playgroud)