linrongbin
linrongbin

Reputation: 3361

How to apply BOOST_PP_CAT twice to shorter c++ duplicate code?

I need to write lots of code like this (actually it's flex rule file):

true { return yy::parser::make_T_TRUE(yy::parser::token::T_TRUE, yy::location()); }
false { return yy::parser::make_T_FALSE(yy::parser::token::T_FALSE, yy::location()); }
try { return yy::parser::make_T_TRY(yy::parser::token::T_TRY, yy::location()); }
catch { return yy::parser::make_T_CATCH(yy::parser::token::T_CATCH, yy::location()); }
finally { return yy::parser::make_T_FINALLY(yy::parser::token::T_FINALLY, yy::location()); }

You could see that if I have a macro like this:

#define MAKE(t) return yy::parser::make_ ## t (yy::parser::token:: ## t, yy::location())

Then I could write much less duplicate code, life will be easier:

true { MAKE(T_TRUE); }
false { MAKE(T_FALSE); }
try { MAKE(T_TRY); }
catch { MAKE(T_CATCH); }
finally { MAKE(T_FINALLY); }

But ## or BOOST_PP_CAT could not been invoke twice in one line, the second expand will not work.

Any idea how to solve this issue ?

Upvotes: 0

Views: 135

Answers (1)

Łukasz Ślusarczyk
Łukasz Ślusarczyk

Reputation: 1864

You need ## in the first place only, where you create a new identifier make_t. In the second place use t without ## because :: well separates t from other tokens in macro.

#define MAKE(t) return yy::parser::make_ ## t (yy::parser::token::t, yy::location())

true { MAKE(T_TRUE); }
false { MAKE(T_FALSE); }
try { MAKE(T_TRY); }
catch { MAKE(T_CATCH); }
finally { MAKE(T_FINALLY); }

Invoking preprocessing by g++ -E test.cpp gives

true { return yy::parser::make_T_TRUE (yy::parser::token::T_TRUE, yy::location()); }
false { return yy::parser::make_T_FALSE (yy::parser::token::T_FALSE, yy::location()); }
try { return yy::parser::make_T_TRY (yy::parser::token::T_TRY, yy::location()); }
catch { return yy::parser::make_T_CATCH (yy::parser::token::T_CATCH, yy::location()); }
finally { return yy::parser::make_T_FINALLY (yy::parser::token::T_FINALLY, yy::location()); }

Upvotes: 1

Related Questions