我可以定义一个指向std :: function类型对象的函数指针吗?

ror*_*oro 9 c++ lambda c++11

类似于以下内容:

#include <functional>

int main()
{
    std::function<int(int)> func = [](int x){return x;};
    int* Fptr(int) = &func; //error
}
Run Code Online (Sandbox Code Playgroud)

我得到的错误是

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
Run Code Online (Sandbox Code Playgroud)

从lambda函数到函数指针的更直接的方法也是有用的.

mol*_*ilo 19

int* Fptr(int)
Run Code Online (Sandbox Code Playgroud)

声明一个函数"Fptr",它接受int并返回int*.

函数指针声明看起来像

int (*Fptr)(int)
Run Code Online (Sandbox Code Playgroud)

此外,std::function<int(int)>不是lambda函数的类型,但lambda函数可以隐式转换为该类型.

幸运的是,(非捕获)lambda函数可以隐式转换为函数指针,因此从lambda函数到函数指针的最直接方法是

int (*Fptr)(int) = [](int x){return x;};
Run Code Online (Sandbox Code Playgroud)

  • 哇,+1,因为非捕获lambda可以被视为一个函数指针,很高兴知道. (2认同)