首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用decltype和auto推导const (return)类型

使用decltype和auto推导const (return)类型
EN

Stack Overflow用户
提问于 2018-06-06 05:11:03
回答 1查看 96关注 0票数 0

为什么decltype从变量推导出const,而不是从函数推导出呢?

代码语言:javascript
复制
const int f()
{
    const int i = 1;
    return i;
}
decltype(auto) i_fromFunc = f(); // i_fromFunc is of type 'int'

const int i = 1;
decltype(auto) i_fromVar = i; // i_fromVar is of type 'const int'

具有更多演绎变体(see at compiler explorer)的示例。

代码语言:javascript
复制
const int func()
{
    const int i = 1;
    return i;
}

decltype(auto) funcDecltype()
{
    const int i = 1;
    return i;        
}

auto funcAuto()
{
    const int i = 1;
    return i;
}

void DeduceFromFunc()
{
    decltype(auto) i = func(); // i is of type 'int', similar to auto i = func()
    i = 2;
    decltype(auto) iDT = funcDecltype(); // iDT is of type 'int', similar to auto iDT = funcDecltype()
    iDT = 2;
    decltype(auto) iA = funcAuto(); // iA is of type 'int', similar to auto iA = funcAuto().
    iA = 2;

    // For the sake of completeness:

    const auto ci = func(); // const int
    //ci = 2; // Not mutable.

    //auto& iRef = func(); // non const lvalue of 'int&' can't bind to rvalue of 'int'
    const auto& ciRef = func(); // const int &
    //ciRef = 2; // Not mutable.

    auto&& iRV = func(); // int &&
    iRV = 2;
    const auto&& ciRV = func(); // const int &&
    //ciRV = 2; // Not mutable.
}

const int gi = 1;

void DeduceFromVar()
{
    auto i_fromVar = gi; // i_fromVar is of type 'int'.
    i_fromVar = 2;
    decltype(auto) iDT_fromVar = gi; // iDT_fromVar is of type 'const int'
    //iDT = 2; // Not mutable.

    // For the sake of completeness:
    auto& iRef = gi; // reference to const int
    //iRef = 2; // Not mutable.
    auto&& iRVRef = gi; // rvalue ref to const int
    //iRVRef = 2; // Not mutable.
}

int main()
{
    DeduceFromFunc();
    DeduceFromVar();
}

为什么iDT_fromVar的恒定性不同于i_fromVar?(vars的decltype(auto)auto )

为什么iDT_fromVar的恒定性不同于iDT?(来自上面的问题)

为什么i_fromVari/iDT/iA具有相同的不变性,而iDT_fromVariDT没有相同的不变性?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-06 06:28:35

没有非类类型的const prvalue。函数const int f()基本上等同于int f()

C++17中的相关条款为expr/6:

如果prvalue最初具有类型“cv T”,其中T是cv未限定的非类、非数组类型,则在进行任何进一步分析之前,表达式的类型将调整为T

如果使用类类型而不是int作为返回类型来尝试类似的代码,您将看到不同的行为。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50708988

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档