What does a constant mean in an automatic return declaration with a return type?
I need to return a constant reference from a function. This code does the following:
auto test()->add_lvalue_reference<const int>::type
{
static int i{50};
return i;
}
int & i{test()}; // doesn't compile
But this snippet, which looks painfully similar, gives the wrong result:
auto const test()->add_lvalue_reference<int>::type
{
static int i{50};
return i;
}
int & i{test()}; // compiles thougth test() returned a const
I moved the keyword const
from the type declaration to the return declaration.
At first I thought that after deduction, the function signature became in the second case:
int & const test(); // not valid - const qualifiers cannot be applied to int&
This is invalid C ++. But with a auto
specifier, it compiles.
So my question is, what does it mean const
in the return type of an auto-return function? Or perhaps it threw it off?
source to share
auto const test()->add_lvalue_reference<int>::type
This is ill-formed, see [dcl.fct] / 2 (in the case where a return type is used, the return type " T
must be the only type specifier auto
").
source to share