Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

stdbind

Im trying to wrap a passed in function inside a try-catch clause so that I can catch exceptions thrown by it and do some cleanup before re-throwing. I have written sample code that replicates my compile bug.

#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;
}

I can't seem to figure out how to pass in a function pointer into either the lambda expression or the bind call. It seems to report an error at the call to bound(). Can someone give some advice or tell me if there is something I'm misunderstanding?

like image 846
sibtx13 Avatar asked Nov 12 '22 22:11

sibtx13


1 Answers

Your problem is actually rather simple: the type deduced for F&& happens to be void(int) rather than void(*)(int). However, you cannot copy a function while you can copy a function pointer. That is, there is a one character fix to your problem:

gen(&foo, 5);

Pass a pointer to the function rather than the function.

like image 185
Dietmar Kühl Avatar answered Nov 15 '22 13:11

Dietmar Kühl