Question

To print several fields of a struct, I have to say the following line repeatedly:

cout << "field1=" << ptr->get_field1()

So I defined the following macro, and use it like this:

#define FIELD(s, id) << s"=" << ptr->get_##id()

FIELD("field1", field1);
FIELD("field2", field2);

This works. But I have to mention the same name twice in the macro - once as a string, another time as a variable. Is there a better way to do it?

(The title of this question does not exactly indicate the question, but I could not think of a more appropriate short combination of words. Sorry about that!)

Was it helpful?

Solution

You should stringify id:

#define FIELD(id) << #id "=" << ptr->get_##id()

FIELD(field1);   // << "field1" "=" << ptr->get_field1()
FIELD(field2);   // << "field2" "=" << ptr->get_field2()

LIVE EXAMPLE

For FIELD(field1), it partly results in this expression:

"field1" "="

which is two literal strings put side-by-side. These two are then concatenated, resulting in a string equivalent to "field1=".

OTHER TIPS

This should work:

#define FIELD(id) << #id "=" << ptr->get_##id()

The # operator in a macro means "make this into a string".

'#' does the trick:

#define FIELD(s) << #s"=" << ptr->get_##s()

or even:

#define FIELD(i)  << "field"#i"=" << ptr->get_field##i() 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top