Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use typedef of function signature as type parameter to std::function?

There must be a difference between a typedef of a function and the use of a bare function type when used as a template type parameter.

I.e., consider

#include <functional>

typedef std::function<void(int)> TF1;

typedef void(*FooFn)(int);
typedef std::function<FooFn>     TF2;

int main() {
    TF1 tf1;
    TF2 tf2;
    return 0;
}

I can create a TF1 but not a TF2 (error: aggregate 'TF2 tf2' has incomplete type and cannot be defined). (See ideone example.)

Is there a way to use a typedef of a function (signature) as a template type parameter; specifically, as the type parameter to std::function?

(No C++11 tag because I'm interested in boost::function as well on non-modern compilers. But a C++11 answer would also be appreciated, if the language changed in some way to enable this.)

like image 989
davidbak Avatar asked Jan 31 '18 00:01

davidbak


1 Answers

std::function needs a function type, while FooFn is a pointer (to function) type, not a function type. Use the metaprogramming helper template remove_pointer to convert it:

typedef std::function<std::remove_pointer<FooFn>::type> TF2;
like image 108
Chris Dodd Avatar answered Sep 22 '22 15:09

Chris Dodd