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

c – 编译器是否为每个lambda生成不同的类型?

发布时间:2020-12-16 10:06:29 所属栏目:百科 来源:网络整理
导读:Disclaimer: Do not use the code in this question. It invokes undefined behaviour. The core statement of the question,whether the compiler generates a new type for each lambda,and the corresponding answer remain valid. 为了获取一个带有捕获

Disclaimer: Do not use the code in this question. It invokes undefined behaviour. The core statement of the question,whether the compiler generates a new type for each lambda,and the corresponding answer remain valid.

为了获取一个带有捕获的lambda的函数指针,我想出了以下技巧:

auto f = [&a] (double x) { return a*x; };
static auto proxy = f;
double(*ptr)(double) = [] (double x) { return proxy(x); };
// do something with ptr

我将lambda与一个捕获(可能是一个函数参数)分配给函数内部的静态变量,所以我不必在另一个lambda中使用它时捕获它.然后另一个无捕获的lambda可以快乐地衰减到一个函数指针,我可以传递给一些共享库.

现在可以尝试概括一下:

template < typename F >
decltype(auto) get_ptr(F f)
{
  static auto proxy = f;
  return [] (auto ... args) { return proxy(args...); };
}

但是,由于代理是静态变量,因此每次调用函数时都会覆盖它.因为它是一个模板,我认为它只有在我调用相同的实例化时才会被覆盖,即每个实例化都有它自己的静态代理.

不过,以下作品:

#include <cassert>

template < typename F >
decltype(auto) get_ptr(F f)
{
  static auto proxy = f;
  return [] (auto ... args) { return proxy(args...); };
}

int main()
{
  auto f1 = [ ](double,double) { return 1; };
  auto f2 = [=](double,double) { return 2; };
  auto f3 = [&](double,double) { return 3; };
  auto f4 = [&](double,double) { return 4; };
  auto f5 = [ ](double,double) { return 5; };

  int(*p1)(double,double) = get_ptr(f1);
  int(*p2)(double,double) = get_ptr(f2);
  int(*p3)(double,double) = get_ptr(f3);
  int(*p4)(double,double) = get_ptr(f4);
  int(*p5)(double,double) = get_ptr(f5);

  assert( p1(0,0) == 1 );
  assert( p2(0,0) == 2 );
  assert( p3(0,0) == 3 );
  assert( p4(0,0) == 4 );
  assert( p5(0,0) == 5 );
}

这看起来很可疑,因为对于get_ptr(f1)和get_ptr(f5),人们可能期望推导出相同的类型.但是,lambda是编译器生成的结构,似乎编译器会为每个lambda生成不同的类型,无论之前的lambda是否可以重用.

因此,在编译器肯定会为每个lambda生成不同类型的情况下,上述技巧对我非常有用.如果不是这种情况,我的黑客的泛化就没用了.

解决方法

从草案规范(具体是n3376),5.1.2.3(强调我的).

The type of the lambda-expression (which is also the type of the closure object) is a unique,unnamed non-union class type — called the closure type…

(编辑:李大同)

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

    推荐文章
      热点阅读