Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define a function pointer pointing to an object of std::function type?

Tags:

c++

c++11

lambda

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.

like image 448
roro Avatar asked Mar 18 '16 07:03

roro


People also ask

Can a pointer refer to any type?

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.

Can a pointer point to a function?

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.

How do you call a function from a pointer object?

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


1 Answers

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;};
like image 173
molbdnilo Avatar answered Oct 05 '22 23:10

molbdnilo