Vladimir Yanakiev Vladimir Yanakiev - 1 year ago 67
C Question

wrap of functions avoid duplicating

I have third party C library. I want to use it in c++
Every function return error code.
when i have to use it I have to write code like this:

int err;

I want to wrap this functions and avoid code duplication of check. Every of this librabry function have different number parameters. What will be a good design for this?

Answer Source

/edit 4: The C++11-Way using variadic templates, inspired by Gill Bates' solution:

template <typename T, class ...A> int CallWrapper(T func, A... args) {
    int error = func(args...);
    return error;

CallWrapper(libFun2, 4711);
CallWrapper(libFun3, 42, 23);

/edit 5: older solutions, beginning with first solution:

#define LIBFUN1() do { \
    int err = libFun1(); \
    check(err); \
} while (0)

#define LIBFUN2() do { \
    int err = libFun2(); \
    check(err); \
} while (0)


Put the #defines in some header file. Please note the MISSING semicolon after the while (). This way, you can naively use LIBFUN1() and so on in any context, where a statement is allowed like if (...) LIBFUN1(); else LIBFUN2();

/edit 3: Instead of using #defines, static inline functions would do the job too:

static inline int checked_libFun1() {
    int err = libFun1();
    return err;

static inline int checked_libFun2() {
    int err = libFun2();
    return err;


/edit 2: @Myst suggested to use variadic macros that contain the name of the function to call. This could look like this:

#define call_void(name) do { \
    int err = name(); \
    check(err); \
} while (0)

#define call_args(name, ...) do { \
    int err = name(__VA_ARGS__); \
    check(err); \
} while (0)

call_args(libFun2, 42);

The two macros are needed because you have to distinguish between functions not accepting any arguments and functions accepting any number of arguments greater one. So, here, libFun2(42) would be called

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download