C ++ 11 lambda return reference

I have some problems with link return from 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 one and the same.

+4
source share
1 answer

lambda prints the return type as specified in auto. auto ret = i;prints rethow int.

One solution is to explicitly specify the type of the return value 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;
};

, decltype .

, , auto decltype(auto).

+18

Source: https://habr.com/ru/post/1686432/


All Articles