Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

c++ - Using commas inside a macro without parenthesis: How can I mix and match with a template?

Consider a simple macro:

#define ECHO(x) x

ECHO(foo(1, 2))

This produces the exact output we expect:

foo(1, 2)

The above example works because the parenthesis adjacent to the function call are recognized by the preprocessor.

Now consider what happens if I use a template instead of a function call:

ECHO(template<int, bool>)

This causes an error because the preprocessor interprets the template<int and the bool> as two separate arguments to the macro. The preprocessor doesn't recognize <> for scope!

Is there anyway to use a template like this in a macro?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
#define COMMA ,
ECHO(template<int COMMA bool>)

A little painful, but it works.

FWIW, if the syntax for the argument allows ()s, you don't need the substitution, e.g.,

ECHO((a, b))

will work for a single argument macro but that doesn't work in all cases (including yours).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...