Hopefully I can ask this clearly. Basically I'm wondering if I have a structure like so:

struct MyStruct
{
char fieldA[20];
char anotherField[15];
int andAnother;
char lastField[30];
};

Is there a way to dynamically print out it's contents?

[fieldA] = "ABCDE"
[anotherField] = "TEST"
[andAnother] = 5
[lastField] = "WHATEVER"

With the capability of sending it a completely different structure (different fields, different sizes, different number of fields, etc.) and it could do the same. I know this is possible in Java using reflection, etc. but wondering if there is a C++ alternative (or close approximation). Note that I would be satisfied even if it required some sort of precompilation for it to work...

Dani AI

Generated

The need describes — printing an unknown struct's field names and values from one generic routine — is common, but standard C++ has no built‑in runtime reflection to enumerate member names. 's OO suggestion (per‑type virtual print) is the simplest, safest approach when you control each type; is also right that languages with reflection (Java/C#) make this much easier. Below are realistic C++ patterns, tradeoffs, and a compact example you can apply today.

If you can add a tiny bit of per‑type boilerplate, an X‑macro (or a small code generator) gives the best balance: you declare fields once and auto‑generate struct members plus a print routine. This keeps printing consistent and avoids manual per‑field code scattered everywhere. Example pattern:

#define PERSON_FIELDS \
  X(name, char[32]) \
  X(age, int) \
  X(score, double)

struct Person {
  #define X(n,t) t n;
  PERSON_FIELDS
  #undef X
};

template<typename T>
void print_field(const char* name, const T& v) { std::cout << "[" << name << "] = " << v << '\n'; }

template<std::size_t N>
void print_field(const char* name, const char (&arr)[N]) { std::cout << "[" << name << "] = \"" << arr << "\"\n"; }

void print(const Person& p) {
  #define X(n,t) print_field(#n, p.n);
  PERSON_FIELDS
  #undef X
}

If zero boilerplate is required, consider two paths: (1) code generation with Clang LibTooling to parse headers and emit print/metadata functions at build time (generates names and handles access control by placing generated code where it can befriend the class), or (2) Boost.PFR / similar libraries to iterate aggregate members without macros — note Boost.PFR can print values but not member names, and requires aggregate types/C++17+.

Cautions: watch private members (codegen or friend declarations needed), pointers and lifetime issues, padding/endianness if doing raw memory walks, and strict‑aliasing UB if you reinterpret memory. For production, prefer explicit generated printers or registration macros rather than fragile runtime hacks.

Recommended Answers

All 4 Replies

You basically want a print struct function? (That works for any struct)

Sounds like you don't want a struct at all but rather a class. Or rather a set of classes that all inherit from a base class that has a virtual print() function. Then all the child classes would have to define a print class that printed their data and instantiate the function.

That would be a sensible way of doing it.

A completly insane way of doing it would be to make a struct Type that contains:
* Data type
* Data length
* Data

Then make a set of structs that contain
* A counter of how many variables are in this struct
* An array of pointers to the Types

You can now code something that takes one of your structs, looks up how many data items are in it, accesses them via the area, when it accesses them it findout what type they are and if needed how big they are, then it uses the correct print method to show the output.

Avoid doing this if you can? (There's definitly a well researched way of doing it as exactly this is needed in order to get from C to C++ which is written in C - but why redo the work???)

That's the thing - I don't want to have to write a separate print function for each class. I basically want to have the ability to get information about the fields of the class without knowing anything about it. (in the same way I can do typeinfo( whatever).name(). (I think what I'm saying is yes, I want the insane way!) This way I can code it once and send any struct to it.

I hope you need this for a good reason... it's not the most efficient way of doing things, or the easiest code from someone else to then understand. In the long run I think you're better off not using such a function unless there is a very good reason for it.

Anyway best of luck.

Maybe what you really want is a different programming language.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.