I have a macro that implements a retry mechanism that looks like that:
#define RETRY(function_name, param_list, max_attempts, retry_interval_usecs, error_var) \
do { \
int _attempt_; \
\
for (_attempt_ = 0; _attempt_ < max_attempts; _attempt_++) \
{ \
error_var = function_name param_list; \
if (error_var == SUCCESS) \
{ \
break; \
} \
\
usleep(retry_interval_usecs); \
} \
} while (0)
This is functional, but I keep hearing that within a C++ application, defines
are not favorable.
Now I looked into a retry function that takes a function pointer as an argument. But I seem to have missed something since I can't get this code to compile.
Note: This code below is NON-Functional, I thought I can post a simple code to illustrate what I want to do:
void retry(int (*pt2Func)(void* args))
{
const int numOfRetries = 3;
int i = 1;
do
{
//Invoke the function that was passed as argument
if((*pt2Func)(args)) //COMPILER: 'args' was not declared in this scope
{
//Invocation is successful
cout << "\t try number#" << i <<" Successful \n";
break;
}
//Invocation is Not successful
cout << "\t try number#" << i <<" Not Successful \n";
++i;
if (i == 4)
{
cout<< "\t failed invocation!";
}
}while (i <= numOfRetries);
}
int Permit(int i)
{
//Permit succeeds the second retry
static int x = 0;
x++;
if (x == 2 && i ==1 ) return 1;
else return 0;
}
int main()
{
int i = 1;
int * args = &i;
retry(&Permit(args));
}
So Basically my question is:
Is that doable?
All existing answers are C++11, so here's a minor modification to your code to make it work using boost (which is C++03)
//takes any function or function like object
//expected function takes no parameters and returns a bool
template<class function_type>
void retry(function_type function, int numOfRetries = 3)
{
int i = 1;
do
{
//Invoke the function that was passed as argument
if(function())
blah blah blah
and in main
int main()
{
int i = 1;
//bind takes a function and some parameters
//and returns a function-like object with a different parameter set
//in this case, the function Permit, and the first thing it gets passed is i
//this means the resulting function-like object doesn't need any parameters
//return type is the same as the original function
retry(boost::bind(Permit, i));
}