1

Say I create some function in my class:

bool isRisingEdge() {
    return current && !last;
}

I also want to generate overloaded versions of this function that accompany it. For the sake of example, let's say I need to overload it with just two different types; the same two types each time. Each overload first calls some function (say process()) first, then return my original function.

bool isRisingEdge(Signal signal) {
    process(signal);
    return isRisingEdge();
}

bool isRisingEdge(Button button) {
    process(button);
    return isRisingEdge();
}

I have many such is...() functions that I want to overload in my class. I could define a macro to help me:

#define CREATE_OVERLOADED_FUNCTION(func_, type_) \
type_ func_(Signal signal) { \
    process(signal); \
    return func_(); \
} \
type_ func_(Button button) { \
    process(button); \
    return func_(); \
}

...and then use this macro rather than typing out the overloads.

bool isRisingEdge() {
    return current && !last;
}

CREATE_OVERLOADED_FUNCTION(isRisingEdge, bool)

bool isFallingEdge() {
    return !current && last;
}

CREATE_OVERLOADED_FUNCTION(isRisingEdge, bool)

etc


My question is this:

Should I be using a macro for a simple purpose like this, or is it better to manually type it out?

Is there a better, non-macro solution?

Macros are shunned by the C++ community, but the Don't Repeat Yourself principle is very important too, and I don't know which "wins".

Jetroid
  • 25
  • 7

0 Answers0