![](/img/trans.png)
[英]How can I pass a pointer to pointer to a function using the pointer it is pointing to?
[英]Can I define a function pointer pointing to an object of std::function type?
類似於以下內容:
#include <functional>
int main()
{
std::function<int(int)> func = [](int x){return x;};
int* Fptr(int) = &func; //error
}
我得到的錯誤是
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
從lambda函數到函數指針的更直接的方法也是有用的。
int* Fptr(int)
聲明一個函數“Fptr”,它接受一個int
並返回int*
。
函數指針聲明看起來像
int (*Fptr)(int)
此外, std::function<int(int)>
不是lambda函數的類型,但是lambda函數可以隱式轉換為該類型。
幸運的是,(非捕獲)lambda函數也可以隱式轉換為函數指針,因此從lambda函數到函數指針的最直接方法是
int (*Fptr)(int) = [](int x){return x;};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.