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...

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.