2

I have an assert macros which looks like:

#define ASSERT(condition, ...) \
  (condition) ? (void)0 : MyLogFunction(__LINE__, __VA_ARGS__)

MyLogFunction is a variadic template too:

template<typename... Args>
void MyLogFunction(int line, const Args&... args) {/*code*/}

Everything works well except the case when I don't want to insert additional information into assert call.

So this works nice:

ASSERT(false, "test: %s", "formatted");

But this isn't:

ASSERT(false);

I believe there is a way to handle situation when no variadic args has has been passed into macro call and there is a way to insert something like simple string "" instead of __VA_ARGS__

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Max Frai
  • 61,946
  • 78
  • 197
  • 306
  • C++11 adds variadic argument lists for macros. It stipulates that there shall be at least one argument corresponding to the ellipsis (ISO/IEC 14882:2011 §16.3 Macro Replacement, ¶4, ¶12). It is likely that GCC provides alternatives (`gcc` has non-standard mechanisms to handle 0 variable arguments, so `g++` probably does too), but it isn't standard. I recommend always providing a value: `ASSERT(false, "false");` as it is portable. – Jonathan Leffler Aug 11 '13 at 05:48

2 Answers2

0

There is no portable way to do it. Have a look at http://en.wikipedia.org/wiki/Variadic_macro

0

Not really a solution for the macros, but a simple workaround would be to provide a helper variadic function template, which can get 0 parameters and do the condition checking there:

#define ASSERT(...) \
  MyLogHelper(__LINE__, __VA_ARGS__)

template<typename... Args>
void MyLogFunction(int line, const Args&... ) {/*code*/}

template<typename... Args>
void MyLogHelper(int line, bool condition, const Args&... args)
{
    if (!condition) MyLogFunction(line,args...);
}
v154c1
  • 1,698
  • 11
  • 19