加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 03:21:24 所属栏目:百科 来源:网络整理
导读:类似以下内容: #include functionalint main(){ std::functionint(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)’
类似以下内容:
#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)

此外,标准::功能< INT(INT)>不是您的lambda函数的类型,但是您的lambda函数可以隐式转换为该类型.

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

int (*Fptr)(int) = [](int x){return x;};

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读