Kepler-229c Kepler-229c - 2 months ago 16
C++ Question

Variadic template for processing method result

Suppose I have a class with some number of methods:

class Foo {
bool someMethodA(int someParamA, double someParamB, int someParamC);
bool someMethodB(double someParamA);
bool someMethodC(double someParamA);
...
}


Each method has a different signature. Is there a convenient way to call these methods such that a notifier method is called on true (success)?

notifySuccess();


The macro to do this is:

// Call a function notifyAll() on success
#define NOTIFY_ON_SUCCESS(func) \
bool success = func; \
if (success) { \
notifySuccess(); \
} \
return success;


It's been suggested that there's a way to do this using variadic templates instead? Something like:

template <typename... ARGS>
bool CallImplAndNotify(bool (&SceneImpl::*func)(ARGS...), ARGS... args) {
bool result = func(args...);
...
}

Answer

It seems that a simple function do the trick:

bool NotifyOnSuccess(bool b) {
   if (b) {
       notifySuccess();
   }
   return b;
}

and call it:

NotifyOnSuccess(foo.someMethodA(42, 5.1, 69));
NotifyOnSuccess(foo.someMethodB(5.1));