微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

类似以下内容
#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;};

原文地址:https://www.jb51.cc/c/111763.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐