I am working on a thread pool and to avoid long qualifier names I would like to use typedef
declaration.
But it is not as easy as it seems to be:
typedef unsigned ( __stdcall *start_address )( void * ) task;
When I tried it that way I got:
error C3646: 'task' : unknown override specifier
error, after playing for a little while with this declaration I'm stuck and can't find any reasonable solution to use to declare such type of typedef
.
If we defined a type SigCatcher as an alias for the pointer to function type: typedef void (*SigCatcher)(int); then we could declare signal() using: SigCatcher signal(int sig, SigCatcher func);
Function Pointer Syntaxvoid (*foo)( int ); In this example, foo is a pointer to a function taking one argument, an integer, and that returns void. It's as if you're declaring a function called "*foo", which takes an int and returns void; now, if *foo is a function, then foo must be a pointer to a function.
The syntax of typedef is as follows: Syntax: typedef data_type new_name; typedef : It is a keyword. data_type : It is the name of any existing type or user defined type created using structure/union.
A typedef, or a function-type alias, helps to define pointers to executable code within memory. Simply put, a typedef can be used as a pointer that references a function.
The Basic syntax of function pointers We can think of function pointers like normal C++ functions. Where void is the function's return type. *fun_ptr is a pointer to a function that takes one int argument. It's as if we are declaring a function called *fun_ptr which takes int and returns void .
It defines a pointer-to-function type. The functions return void, and the argument list is unspecified because the question is (currently, but possibly erroneously) tagged C; if it were tagged C++, then the function would take no arguments at all.
When creating a typedef
alias for a function pointer, the alias is in the function name position, so use:
typedef unsigned (__stdcall *task )(void *);
task
is now a type alias for: pointer to a function taking a void
pointer and returning unsigned
.
Since hmjd's answer has been deleted...
In C++11 a whole newsome alias syntax has been developed, to make such things much easier:
using task = unsigned (__stdcall*)(void*);
is equivalent the to typedef unsigned (__stdcall* task)(void*);
(note the position of the alias in the middle of the function signature...).
It can also be used for templates:
template <typename T>
using Vec = std::vector<T>;
int main() {
Vec<int> x;
}
This syntax is quite nicer than the old one (and for templates, actually makes template aliasing possible) but does require a quite newish compiler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With