DEV Community

beto-bit
beto-bit

Posted on

A Function Pointer Wrapper in C++

So you probably already know what are function pointers and how to use them. You also probably know that function pointers have a really ugly syntax.

int func(int a, double b);

int foo() {
    int (*ptr)(int, double) = func;
    return ptr(3, 0.4);
}
Enter fullscreen mode Exit fullscreen mode

But what to do when you want to return a function pointer?
You could use a typedef in order to do that.

int fun(int a, double b);

typedef int (*func_type)(int, double);

func_type bar() {
    return func;
}
Enter fullscreen mode Exit fullscreen mode

But if you don't want to name your function type, you end with something like this.

// The function name is baz and it takes no arguments!
int( *baz(void) )(int, double) {
    return func;
}
Enter fullscreen mode Exit fullscreen mode

But we are talking about C++, so you have probably just used auto, or even worse, returned a slow std::function.
Instead of that, you can use this zero cost template.

It looks overcomplicated (as everything in C++) but is basically a nice type alias with CTAD. So you can do this.

FuncPtr<int(int, double)> foo() {
    FuncPtr temporal = func; // CTAD
    return temporal;
}
Enter fullscreen mode Exit fullscreen mode

I don't really remember when was the first time I saw something like this. So if you find the original, please leave it in the comments! Thanks for reading.

Top comments (2)

Collapse
 
pauljlucas profile image
Paul J. Lucas •

But if you don't want to name your function type ...

I can't think of any reason why anyone would refuse to do that.

Collapse
 
betobit profile image
beto-bit •

I think it is more of a style thing, and naming variables (and types) is usually hard. Thank you for reading!