1

I would like to be able to write a macro CONDITIONALFUNCTION so that

CONDITIONALFUNCTION( FunctionName )
{
    ConditionalExpression()
}

expands to

bool FunctionName( const Arguments& args )
{
    return ConditionalExpression();
}

Is this even possible?

The closest I can find on SO is this thread:

Possible to define a function-like macro with a variable body?

except unlike in that thread, I have the additional requirement that the "body" within the braces is not a complete valid C++ statement, but rather an expression to be wrapped (effectively) in an 'if' statement.

Please assume I already know this may be impossible, and is almost surely stupid and evil :)

Community
  • 1
  • 1
DSII
  • 429
  • 6
  • 15

3 Answers3

1

I'm going to assume you've got a good reason for using macros in the first place...

It's not possible with the syntax you've given with the question.

The closest workable macro syntax is:

#define CONDITIONALEXPRESSION(f, c) \
bool f( const Arguments& args ) \
{ return c; }

CONDITIONALEXPRESSION(FunctionName, ConditionalExpression())

This will expand to the same as the expanded function in the question

je4d
  • 7,628
  • 32
  • 46
0

Is there any reason why the function body must be defined in the macro? In Microsoft C++, macros like ASSERT() define the actual function separately and then just reference it from the macro.

So the function is always defined but the macro is either equal to calling the function or nothing at all.

Aside from that, for C++ I'd probably use an inline function.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
0

je4d already provided one alternative. I over some other variation:

#define CONDITIONALEXPRESSION(f) \
bool f( const Arguments& args )

#define CONDITIONALRETURN(c) \ 
return (c)

CONDITIONALEXPRESSION(FunctionName)
{
  CONDITIONALRETURN(ConditionalExpression())
}
johannes
  • 15,807
  • 3
  • 44
  • 57