lundi 31 juillet 2017

Call method only if pointer is not nullptr

I have an interface class and a pointer that may be nullptr and if it is I just skip the method call:

if (ptr != nullptr)
{
    ptr->SomeMethod();
}

...

if (ptr != nullptr)
{
    ptr->SomeOtherMethod();
}

...

if (ptr != nullptr)
{
    ptr->SomeMethodThatWasntMentionedBefore();
}

I can improve this code readability with the following macro:

#define CALL_IF_NOT_NULLPTR(ptr, method_call) if (ptr != nullptr) { ptr->method_call; };

CALL_IF_NOT_NULLPTR(ptr, SomeMethod());
CALL_IF_NOT_NULLPTR(ptr, SomeOtherMethod());
CALL_IF_NOT_NULLPTR(ptr, SomeMethodThatWasntMentionedBefore());

Is there any way to do the same without macros (C++11 solutions are preferred)?

Aucun commentaire:

Enregistrer un commentaire