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

在C中援引lambdas的方法是最惯用的?

发布时间:2020-12-16 05:47:58 所属栏目:百科 来源:网络整理
导读:我注意到lambdas都使用函数指针以及使用g的专用函数类型. #include functionaltypedef int(*fptr)(int,int);int apply_p(fptr f,int a,int b) { return f(a,b);}int apply_f(std::functionint(int,int) f,b);}void example() { auto add = [](int a,int b) -
我注意到lambdas都使用函数指针以及使用g的专用函数类型.
#include <functional>

typedef int(*fptr)(int,int);

int apply_p(fptr f,int a,int b) {
  return f(a,b);
}

int apply_f(std::function<int(int,int)> f,b);
}

void example() {
  auto add = [](int a,int b) -> int {
    return a + b;
  };

  apply_p(add,2,3); // doesn't give an error like I'd expect it to
  apply_f(add,3); 
}

我的问题是:哪些是最惯用的?使用另一种的危险和/或好处是什么?

解决方法

I noticed that lambdas both work using function pointers as well as the dedicated function type

如果lambda没有捕获任何东西,那么它可以衰减到一个函数指针.

Which of these are most idiomatic to use?

都不是.如果要存储任意可调用对象,请使用函数.如果您只想创建并使用它,请保持通用:

template <typename Function>
int apply(Function && f,int b) {
     return f(a,b);
}

你可以进一步,使返回和参数类型通用;我会把它作为一个练习.

And what are the dangers and/or benefits of using one over the other?

函数指针版本仅适用于(非成员或静态)函数和非捕获的lambdas,并且不允许任何状态被传递;只有函数本身及其参数.函数类型可以包装任何可调用对象类型,具有或不具有状态,因此更通常是有用的.但是,这具有运行时成本:隐藏包装类型,调用它将涉及虚函数调用(或类似);并且可能需要动态内存分配来保存大型.

(编辑:李大同)

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

    推荐文章
      热点阅读