将函数指针作为参数传递给 std::bind 中的另一个函数
Passing in function pointer as argument to another function in std::bind
我试图将传递的函数包装在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() 时报告错误。有人可以给我一些建议或告诉我是否有误解的地方吗?
你的问题其实很简单:为F&&
推导出的类型恰好是void(int)
而不是void(*)(int)
。但是,不能复制函数,而可以复制函数指针。也就是说,您的问题有一个字符修复:
gen(&foo, 5);
传递指向函数而不是函数的指针。
相关文章:
- boost::bind()类似的东西,但用于函数调用
- PCL:当我在setConditionFunction中使用std::bind 时,没有合适的转换函数
- std::bind 是否实现了 std::ref 和 std::cref 来消除函数调用的歧义?
- std::bind 和 std::函数术语不值为接受 0 个参数?
- 在调用 std::bind 的产品后意外调用析构函数
- 使用 object 中的方法调用带有 std::bind 和 std::function.target 的 C 样式函数
- 我们应该在使用 std::bind 应用之前检查一个不为空的函数吗?
- 为什么 std::bind 静态类型检查传递给函数的参数?
- 对函数库中的语法感到困惑 std::bind
- 如何将参数从函数传递给 std::bind
- 如何在C++中使用 std::bind 函数作为信号处理程序?
- std::bind() 参数列表中函子的执行顺序(可能与函数参数的求值顺序无关)
- 在模板函数参数中使用 std::bind
- boost::bind函数缓冲区的最大大小
- 使用 std::thread & std::bind 在成员函数中启动线程
- 为什么 std::bind 绑定到成员函数时无法编译?
- 如何在 std::bind 中指示给定签名的重载函数?
- std::bind to a std::variant 包含多个 std::函数类型
- 编译使用 libcxx 的套接字函数 bind() 的代码失败
- 带有Boost的泛型函数bind()