Home > database >  Can std::function have a function pointer as the type?
Can std::function have a function pointer as the type?

Time:12-05

Suppose that I have the C-style callback type like below. For C , I could create a std::function type like callback2, and this kind of declaration is all examples I could find. But instead of typing the signature again, can I reuse callback like callback3 below?

If callback3 is possible,

  1. how can I call the callback? Is c.target<callback>(); like below is the correct way to call the callback?

  2. how can I pass a member function? For the common type, I could use worker2([this]() {toBeCalled();}); but worker3([this]() {toBeCalled();}); did not work.

Code

typedef void (*callback)();
typedef std::function<void()> callback2;
typedef std::function<callback> callback3;

void worker(callback c)
{
    c();
}

void worker2(callback2 c)
{
    c();
}

void worker3(callback3 c)
{
    //Is this the way to call the callback?
    c.target<callback>();
}

class Caller
{
public: Caller()
    {
        //worker2([this]() {toBeCalled();});
        worker3(????);
    }
     void toBeCalled()
    {
         std::cout << "toBeCalled()";
    }
};

CodePudding user response:

Can std::function have a function pointer as the type?

No. The class template std::function is defined only for a function type template argument. The template is undefined for all other argument types, including function pointers.

I also recommend against aliasing pointer types in general (there are exceptions to this rule of thumb though). If you avoid it, then you can re-use the alias just fine:

typedef void callback();
typedef std::function<callback> callback2;
// or preferably using the modern syntax
using callback  = void();
using callback2 = std::function<callback>;

void worker (callback* c);
void worker2(callback2 c);

CodePudding user response:

You could use std::remove_pointer on callback. Let's your function type is T and callback is of type T*. std::remove_pointer_t<T*> would give T.

typedef void(*callback)();
typedef std::function<void()> callback1;
typedef std::function<std::remove_pointer_t<callback>> callback2;

void worker(callback c){
    c();
}
void worker1(callback1 c){
    c();
}
void worker2(callback2 c){
    c();
}


int main()
{
    worker([]{std::cout << "callback\n";});
    worker1([]{std::cout << "callback1\n";});
    worker2([]{std::cout << "callback2\n";});
}
/*
Output
callback
callback1
callback2
*/

Now, callback1 and callback2 are aliases to the same.

  • Related