DEV Community

Discussion on: C++ Pointer to Function

Collapse
 
pgradot profile image
Pierre Gradot • Edited

Since C++11, using is generally more readable than typedef:

using Pointer = void (*)();
Enter fullscreen mode Exit fullscreen mode

More generally, with C++11 and above, we now tend to use std::function instead of function pointers as they are able to hold more different types of functions, such as capturing lambdas. Example:

#include <iostream>
#include <functional>

void f() {
    std::cout << "f" << '\n';
}

using Pointer = void (*)();
using Function = std::function<void(void)>;

int main() {

    Pointer pf = f;
    pf();
    Function ff = f;
    ff();

    int a = 42;
    auto lambda = [a]() {
        std::cout << "Lambda a=" << a << '\n';
    };

    Function fl = lambda;
    fl();

//  Pointer pl = lambda; // error: cannot convert 'main()::<lambda()>' to 'Pointer' {aka 'void (*)()'} in initialization
}
Enter fullscreen mode Exit fullscreen mode

Function pointers are still necessary to interface C++ and C codes.

Collapse
 
hi_artem profile image
Artem

Learned a lot from this comment. Thanks!!

Collapse
 
pgradot profile image
Pierre Gradot

Glad it helped : )

There is another use-case for std::function: it can be used to hold a "function object" (also called a "functor":

#include <iostream>
#include <functional>

using Function = std::function<void(void)>;

struct Callable {
    void operator()() {
        std::cout << "callable::operator()()" << '\n';
    }
};

int main() {
    Callable callable;
    Function f = callable;
    f();
}
Enter fullscreen mode Exit fullscreen mode