将函数指针作为参数传递给 std::bind 中的另一个函数

Passing in function pointer as argument to another function in std::bind

本文关键字:函数 bind 另一个 std 指针 参数传递      更新时间:2023-10-16

我试图将传递的函数包装在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);

传递指向函数而不是函数的指针。