1

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?

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

3 Comments

This wouldn't be too difficult in Java. Surprised it's not possible in C++
@KAlistair Indeed, but Java and C++ are actually very different
Java is a managed language. C++ is not. Managed languages are fundamentally different from natively-compiled languages, like C++.
1

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

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.