Search code examples
c++std-function

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


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()";
    }
};

Solution

  • 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);