c++ - String concatenation inside macro -
to print several fields of struct, have following line repeatedly:
cout << "field1=" << ptr->get_field1()
so defined following macro, , use this:
#define field(s, id) << s"=" << ptr->get_##id() field("field1", field1); field("field2", field2);
this works. have mention same name twice in macro - once string, time variable. there better way it?
(the title of question not indicate question, not think of more appropriate short combination of words. sorry that!)
you should stringify id
:
#define field(id) << #id "=" << ptr->get_##id() field(field1); // << "field1" "=" << ptr->get_field1() field(field2); // << "field2" "=" << ptr->get_field2()
for field(field1)
, partly results in expression:
"field1" "="
which 2 literal strings put side-by-side. these 2 concatenated, resulting in string equivalent "field1="
.
Comments
Post a Comment