Why doesn't decltype(auto) return the address of the lvalue?

74 Views Asked by At

I have the following code

decltype(auto) foo(){
    int a = 10;
    return a;
}

I would have expected the type of foo to be

int & foo()

because the a is an lvalue and decltype(a) is a reference.

If I do a very similar thing but obfuscate it with a perfect forwarding lambda I get a different result.

// perfect forwarding lambda
auto identity = [](auto&& i) -> decltype(auto) { return std::forward<decltype(i)>(i); };

decltype(auto) foo(){

    int a = 10;
    return identity(a);
}

the return type of foo become int&

Can anybody enlighten me on the exactly rules for what is happening here?

1

There are 1 best solutions below

0
On

The critical difference as that I had written the identity function incorrectly.

auto identity = [](auto&& i) -> decltype(auto) { 
   return std::forward<decltype(i)>(i); 
};

is not the same as

template <typename T>
decltype(auto) identity(T && v){
    return std::forward<T>(v);
}

the correct implementation of identity as a lambda is

auto identity = [](auto&& i) -> decltype(auto) { 
   return std::forward<decltype((i))>(i); 
};

Note the double set of brackets decltype((i))