Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to proxify any function

Tags:

c++

I use a (C) library with functions taking different parameters but always returning an int greater than zero in case of error:

int functionA(int param1, char param2); /* return an error code on failure, 0 otherwise */
int functionB(LIB_BOOLEAN param1);      /* return an error code on failure, 0 otherwise */
// ...

I would like to turn them all to be exception ready:

if (functionA(param1, param2) > 0)
{ throw std::runtime_error("Method failed"); }

Is it possible to write a template to do it once for all method ?

EDIT: The idea is to avoid checking the result for each functions every time I use them.

like image 683
FloFu Avatar asked Feb 03 '26 00:02

FloFu


1 Answers

Do you mean something like this?

template<typename F, typename... Args>
auto my_invoke(F &&f, Args&&... args) {
    if(std::forward<F>(f)(std::forward<Args>(args)...)) {
        throw std::runtime_error("Method failed");
    }
}

You can call it as;

my_invoke(functionA, 0, 'c');
like image 54
skypjack Avatar answered Feb 05 '26 13:02

skypjack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!