Something like the following:
#include <functional>
int main()
{
std::function<int(int)> func = [](int x){return x;};
int* Fptr(int) = &func; //error
}
The errors I get are
temp.cpp: In function ‘int main()’:
temp.cpp:6:15: warning: declaration of ‘int* Fptr(int)’ has ‘extern’ and is initialized
int* Fptr(int) = &func; //error
^
temp.cpp:6:20: error: invalid pure specifier (only ‘= 0’ is allowed) before ‘func’
int* Fptr(int) = &func; //error
^
temp.cpp:6:20: error: function ‘int* Fptr(int)’ is initialized like a variable
A more direct way to go from lambda function to function pointer would be useful to know as well.
Every pointer is of some specific type. There's a special generic pointer type void* that can point to any object type, but you have to convert a void* to some specific pointer type before you can dereference it.
A pointer to a function points to the address of the executable code of the function. You can use pointers to call functions and to pass functions as arguments to other functions. You cannot perform pointer arithmetic on pointers to functions.
Using a pointer-to-member-function to call a function Calling the member function on an object using a pointer-to-member-function result = (object. *pointer_name)(arguments); or calling with a pointer to the object result = (object_ptr->*pointer_name)(arguments);
int* Fptr(int)
declares a function "Fptr" that takes an int
and returns int*
.
A function pointer declaration looks like
int (*Fptr)(int)
Further,std::function<int(int)>
is not the type of your lambda function, but your lambda function can be implicitly converted to that type.
Fortunately, a (non-capturing) lambda function can also be implicitly converted to a function pointer, so the most direct way from lambda function to function pointer is
int (*Fptr)(int) = [](int x){return x;};
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