Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

    MEDevel.com: Open-source for Healthcare and Education

    Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

    Visit Medevel

  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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading