vendredi 31 mars 2017

What does const means in auto return declaration with trailing return type?

I need to return a const reference from the function. This code does the thing:

auto test()->add_lvalue_reference<const int>::type
{
    static int i{50};
    return i;
}

int & i{test()}; // doesn't compile

But this snippet, that looks painfully similar, gives an incorrect 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 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 not a valid c++. But with auto specifier it compiles.

So my question is what does const means in function return type with auto trailing return? Or maybe it's discarded?

Aucun commentaire:

Enregistrer un commentaire