Search code examples
c++macrosc-preprocessorstringification

String concatenation inside macro


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!)


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