2017-03-31 53 views
3

我需要从函数返回一个const引用。此代码的东西:const在带有尾随返回类型的自动返回声明中意味着什么?

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

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

但这个片段中,看起来痛苦相似,给出了一个不正确的结果:

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

int & i{test()}; // compiles thougth test() returned a const 

我从类型声明回报声明移动关键字const

起初,我以为,是扣除函数签名在第二种情况下变成了:

int & const test(); // not valid - const qualifiers cannot be applied to int& 

这不是一个有效的C++。但用auto说明符编译。

所以我的问题是const是什么意思在函数返回类型与自动追尾返回?或者它被丢弃了?

+3

恭喜,您发现了一个编译器错误。 –

回答

5
auto const test()->add_lvalue_reference<int>::type 

这是形成不良的,见[dcl.fct]/2(在一个尾返回型被使用的情况下,“T应为单类型说明符auto”)。

+0

你说得对。我需要先在不同的编译器上测试。 Clang和msvc拒绝与gcc相反编译。 – nikitablack