0

I have the following macro:

#define MyAssert(condition, ...) CallMyAssertFunctionInCpp(condition, __VA_ARGS__)

__VA_ARGS__ is the error message of type char *, I would like to make it equal to "" if __VA_ARGS__ is empty.

How to do that? I'm not sure I can do condition in macro but maybe there is a trick?

8
  • 4
    if it's C++ then why don't just use templates? It's much easier and cleaner Commented Sep 14, 2021 at 8:59
  • 1
    IIRC it's not possible using macros. Almost all problems with function-like macros can be solved by using actual functions instead. For example this one. where you can have one templated overload taking arguments and one taking no arguments. Commented Sep 14, 2021 at 8:59
  • I have to do that using macro Commented Sep 14, 2021 at 9:04
  • Why do you have to use a macro? What is the actual and underlying problem you need to solve with a macro like this? What are the full list of requirements and limitations? Commented Sep 14, 2021 at 9:12
  • stackoverflow.com/questions/11761703/… and overload for zero and one argument. Commented Sep 14, 2021 at 9:45

1 Answer 1

3

As suggested in comments, it's easy to achieve using C++ templates:

#include <utility>

const char * CallMyAssertFunctionInCpp(bool condition, int arg);

template <typename... T>
const char * MyAssert(bool condition, T... args) {
    if constexpr (sizeof...(T) == 0) {
        return "";
    } else {
        return CallMyAssertFunctionInCpp(condition, std::forward<T>(args)...);
    }
}

void example() {
    MyAssert(true);
    MyAssert(true, 42);
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.