Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing the values of an instantiated structure without using the names of the fields in C++

Tags:

c++

string

struct

Can I do it?

For example consider the following structure:

struct bag {
     string fruit;
     string book;
     string money;
};

I want to print the values of the fields of an instance of the structure bag in a sequentially form and obtain an output like this:

apple
Computer Networking, A top-down Approach
100

But without using the names of the fields(fruit, book and money). Any help would be appreciated. The only information I know it is that all the fields are C++ strings.

like image 245
Renato Sanhueza Avatar asked Dec 07 '25 07:12

Renato Sanhueza


1 Answers

Although C++ does not have reflection, you can make your own reflection tools with Boost.Hana. Here is a complete program that iterates over the members of your struct, printing their names and values.

Hana requires a modern, C++14-compliant compiler, which means recent versions of Clang or GCC 6+ are your only options right now for this code.

Edit: This code now uses BOOST_HANA_ADAPT_STRUCT instead of 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
like image 195
Barrett Adair Avatar answered Dec 09 '25 19:12

Barrett Adair



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!