【发布时间】:2019-04-03 14:49:41
【问题描述】:
我有一个实现重试机制的宏,如下所示:
#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)
这是功能性的,但我一直听说在 C++ 应用程序中,defines 不受欢迎。
现在我研究了一个以函数指针作为参数的重试函数。但我似乎错过了一些东西,因为我无法编译这段代码。
注意:下面的这段代码是非功能性的,我想我可以发布一个简单的代码来说明我想要做什么:
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));
}
所以基本上我的问题是:
- 如何将具有不同参数(类型和数量)的通用函数传递给重试方法?没有将函数封装在一个类中?
这可行吗?
【问题讨论】:
-
这比你想象的要复杂,因为
Permit(args)会在那里执行它,然后你试图将生成的int的地址传递给retry函数。你需要的是std::bind。 -
在 C++03 中,我相信您会被“封装函数”及其在类类型中的参数所困扰,以便在没有参数的情况下调用它。
-
@Mooing Duck,我正在研究 boost::bind,但我不知道这有什么帮助:$。如果我将函数与其参数绑定,我如何将它传递给 retry(..) 你有一个例子吗?
标签: c++ function-pointers