【发布时间】:2012-09-10 04:26:33
【问题描述】:
我试图将传入的函数包装在 try-catch 子句中,以便我可以捕获它抛出的异常并在重新抛出之前进行一些清理。我已经编写了复制我的编译错误的示例代码。
#include <functional>
#include <iostream>
#include <queue>
#include <string.h>
#include <stdexcept>
using namespace std;
void foo(int a){
throw runtime_error("died");
}
template<class F,class ...Args>
void gen(F&& f,Args&&... args){
auto wrap = [](F f,Args... args){
try{
f(args...);
}catch(exception& e){
std::cout << "Caught exception" <<std::endl;
}
};
auto bound = std::bind(wrap, std::forward<F> (f),
std::forward<Args>(args)...);
bound();
}
int main()
{
gen(foo,5);
return 0;
}
我似乎不知道如何将函数指针传递给 lambda 表达式或绑定调用。似乎在调用bound() 时报错。如果我有什么误解,有人可以给我一些建议或告诉我吗?
【问题讨论】:
-
您是否打算将
gen()返回bound以便您可以在其他地方使用它?如果没有,为什么要使用 lambda? -
完全正确,我打算退货。