user11383585
user11383585

Reputation:

How to wrap a function call C++ to assign variables

Is there a way to have a function that executes a different function but carries out the same steps independent of the function?

This example would better portray what I mean:

ret = SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env);
if (!SQL_SUCCEEDED(ret)) {
    printf("SQL Failed\n");
    DisplayError(SQL_HANDLE_STMT, stmt);
}

ret = SQLSetEnvAttr(env, SQL_ATTR_ODBC_VERSION, (void*)SQL_OV_ODBC3, 0);
if (!SQL_SUCCEEDED(ret)) {
    printf("SQL Failed\n");
    DisplayError(SQL_HANDLE_STMT, stmt);
}

I can't think of a more general example other than my specific needs, but the common part here is that I am always checking if the return variable from an SQL function is an error, and then if it is, printing said error. I feel this would be better if it was possible to wrap the error checking in a debug mode, and strip it off in a release mode, but I don't know how to do it. I am hoping that there is an answer along the lines of

SQL(ret, SQLAllocHandle(SQL_HANDLE_ENV, SQL_NULL_HANDLE, &env));

Where wrapping the entire call in a defined SQL function would call any sql function passed in, as well as assigning it to the variable so long as the return types are the same.

I have tried to come up with something such as

#define SQL(a, x) (a = x; if (!SQL_SUCCEEDED(a)) { printf("SQL Failed\n"); DisplayError(SQL_HANDLE_STMT, stmt);})

but this doesn't work.

Upvotes: 0

Views: 84

Answers (1)

cnh003
cnh003

Reputation: 144

You can pass functions by copying or by const reference...

int MyFunction( const std::function<int(void)> & fn )
{
    return fn();
}

int MyFunction2( std::function<int(int)> fn )
{
    return fn(7);
}

and either pass a Lambda

MyFunction([]{ return SomeIntFunction(); });

or a reference to a static function

MyFunction(&StaticIntFunction);

or bind the function

MyFunction(std::bind(&Class::SomeIntFunction, classInstance));

Upvotes: 1

Related Questions