davidbak
davidbak

Reputation: 5999

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.)

Upvotes: 5

Views: 1842

Answers (2)

Chris Dodd
Chris Dodd

Reputation: 126203

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;

Upvotes: 4

imreal
imreal

Reputation: 10348

A std::function object can store any Callable object including a function pointer (you could initialize tf1 with a pointer of type FooFn).

But the template parameters are of type R result type and Args arguments.

template< class R, class... Args >
class function<R(Args...)>;

EDIT: The following example changes the FooFn typedef from function pointer to function type.

https://ideone.com/XF9I7N

Upvotes: 3

Related Questions