K Alistair
K Alistair

Reputation: 15

C++ function to output generic struct

I would like to know how to write a C++ function to print the attributes of a generic struct. For example,

struct a {
std::string field_1;
std::string field_2;
std::string field_3;
};


struct b {
int a;
int b;
int c;
};

The function would take struct of form 'a' or 'b'as inputs and generate outputs. Perhaps a template could be used -- if so how would one build it?

Upvotes: 1

Views: 543

Answers (3)

OutOfBound
OutOfBound

Reputation: 2004

There are two possibilities to work around the missing support for reflections in c++.

The first one is to use std::tuple instead and iterate over it. This can be done explicitly by reflection or nicely wrapped in boost::fusion.

The second posibillity with c++14 is boost::hana. In boost::hana there are structs, that can be iterated over. This is done with the help of preprocessor macros.

If you are still interested, i can post a minimal example here.

Upvotes: 0

Henricus V.
Henricus V.

Reputation: 948

This is currently not possible but might be available in C++17 with static reflection.

See also Compile-time reflection in C++1z?

Upvotes: 1

Sam Varshavchik
Sam Varshavchik

Reputation: 118300

This is not possible in standard C++, it does not work this way. C++ does not have reflection.

Upvotes: 2

Related Questions