gpt4 book ai didi

c++ - 使用 decltype 和 auto 推导 const(返回)类型

转载 作者:行者123 更新时间:2023-11-27 23:55:12 25 4
gpt4 key购买 nike

为什么 decltype推断const来自变量而不是函数?

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 )。

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 ? (decltype(auto)auto 对于变量)

为什么 iDT_fromVar 的常量性不同于 iDT ? (上面的问题)

为什么 i_fromVari/iDT/iAiDT_fromVar 时具有相同的常量和 iDT有没有?

最佳答案

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

C++17中的相关子句是[expr]/6:

If a prvalue initially has the type “cv T ”, where T is a cv-unqualified non-class, non-array type, the type of the expression is adjusted to T prior to any further analysis.

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

关于c++ - 使用 decltype 和 auto 推导 const(返回)类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50708988/

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