C ++ 11 Lambda返回参考 [英] C++11 lambda returning reference

查看:78
本文介绍了C ++ 11 Lambda返回参考的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难从lambda返回引用.这段代码有效:

  std :: function< int *(int *)>功能funct = [](int * i){++ * i;返回我};int j = 0;LOG< ** funct(& j)< j; 

输出:1 1

但不是这个:

  std :: function< int&(int&)>功能funct = [](int& i){++ i;返回我};int j = 0;LOG<< funct(j)<< j; 

构建错误:C:\ Program Files(x86)\ Microsoft Visual Studio 14.0 \ VC \ include \ type_traits:1441:错误:C2440:'return':无法从'int'转换为'int&'

知道为什么吗?对我来说是同一回事.

解决方案

lambda推导返回类型,就像使用 auto 指定的那样. auto ret = i; 会推断出 ret int .

一种解决方案是显式声明lambda的返回类型:

  funct = [](int& i)->集成&{++ i;返回我}; 

如评论中所述,另一种方式是

  funct = [](int& i)->decltype(auto){++ i;返回我}; 

实质上告诉编译器不要做任何推论,而只是使用类型,就好像在返回表达式上使用了 decltype 一样.

如果您对确切的规则感到好奇,请查看文档,其中也包含 auto 上的一部分,以及 decltype(auto)上的一点.

I have some trouble to return a reference from a lambda. This code works :

std::function<int*(int*)> funct;

funct = [](int *i){
    ++*i;
    return i;
};

int j = 0;
LOG<<*funct(&j)<<j;

Output : 1 1

But not this one :

std::function<int&(int&)> funct;

funct = [](int &i){
    ++i;
    return i;
};

int j = 0;
LOG<<funct(j)<<j;

Building error : C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\type_traits:1441: error: C2440: 'return': cannot convert from 'int' to 'int &'

Any idea why? For me it is the same thing.

解决方案

The lambda deduces the return type as if specified with auto. auto ret = i; would deduce ret to be an int.

One solution is to explicitly state the return type of the lambda:

funct = [](int &i) -> int& {
    ++i;
    return i;
};

As mentioned in the comments another way is

funct = [](int &i) -> decltype(auto) {
    ++i;
    return i;
};

which essentially tells the compiler not to do any deduction and to just use the type as if decltype had been used on the return expression.

If you are curious about the exact rules check the documentation which also has a section on auto and a bit on decltype(auto).

这篇关于C ++ 11 Lambda返回参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆