gpt4 book ai didi

c++ - const 在具有尾随返回类型的自动返回声明中意味着什么?

转载 作者:太空狗 更新时间:2023-10-29 20:35:21 26 4
gpt4 key购买 nike

我需要从函数返回一个常量引用。这段代码做的事情:

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 在具有自动尾随返回的函数返回类型中意味着什么?或者它可能被丢弃了?

最佳答案

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

这是错误的,请参阅 [dcl.fct]/2 (在使用 trailing-return-type 的情况下,“T 应该是单个type-specifier auto").

关于c++ - const 在具有尾随返回类型的自动返回声明中意味着什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43143763/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com