sam91
sam91

Reputation: 87

unable to convert return value of std::bind to void function pointer

I am new to functional library. I want to bind a static class method with the object of the class and return a void pointer to the function. I tried using std::bind but it cannot convert a class member function to free floating pointer to the function

Here is a test code that I have:

class base{
    void (*fn)();
    int m_var;
public:
    base(int var): fn(std::bind(print, this)), m_var(var){
        std::cout << "base ctor\n";
        fn(); //something like this. fn should be a void pointer to the function.
    }

    static void print(base *b){
        std::cout << b->m_var << "\n";
    }
};

int main(){
    base *b = new base(5);
    return 0;
}

This is the error I get:

error: cannot convert ‘std::_Bind_helper<false, void (&)(base*), base*>::type’ {aka ‘std::_Bind<void (*(base*))(base*)>’} to ‘void (*)()’ in initialization

I know that I cannot convert class member to a free floating function, but I need the return type of std::bind to be a void pointer as that is an input to one of the external libraries I am using. Any help/suggestion is appreciated.

Upvotes: 2

Views: 2546

Answers (1)

Dmitry Gordon
Dmitry Gordon

Reputation: 2324

Unfortunately you can't convert the result of std::bind to a function pointer and the reasons are quite simple. Let's try to imagine how std::bind could work. You have a function which takes some argument and a value and you want to get something callable that can be called without parameters. The only possible way to do it without generating new code in run-time is to create a functional object which stores the original function and the bound argument with overloaded operator(). Actually std::_Bind_helper is very similar to this description.

So as a result you get an object of some type which has some members. So it cannot be somehow converted to a pointer to the function which cannot store any arguments.

Upvotes: 3

Related Questions