How can I print the structure with the field names?

Suppose I have

struct foo { int bar; double baz; };

      

And struct foo s;

somewhere. I would like to write magic(s)

and get a string or text printed in cout that includes not only the s.bar and s.baz values, but also the "bar" and "baz" identifiers.

I know C ++ doesn't have proper reflection, but maybe something RTTIish (I'm not good at RTTI)? Or perhaps with a little decoration on the class declaration?

Note. Of course I'm asking for a solution that will work for any type, or at least any structure; i can implement operator<<

for foo

.

+3


source to share


2 answers


We may have to wait until C ++ adds expression to the language.

This is actively working WG7 SG7. What is it? WG21 is the International Organization for Standardization (ISO) working group that develops standards for the C ++ language. SG7 is the subgroup responsible for exploring opportunities.



SG7 has a Google Group discussing its current work.

0


source


You can implement:

inline std::ostream& operator<<(
        std::ostream& os, // stream object
        const foo& f
    )
    {
        os << /*ToDo - nice formatting of data members*/
        return os;
    }

      



Then this will work with cout

etc:

foo f; cout << "My foo is " << f << ".";

+2


source







All Articles