gpt4 book ai didi

c++需要清晰的示例来显示 decltype(x) 和 decltype((x)) 之间的区别

转载 作者:太空宇宙 更新时间:2023-11-04 15:16:04 28 4
gpt4 key购买 nike

关于 decltype(x) 和 decltype((x)) 之间的区别,我已经读过很多遍了。一个例子如下。

x is the name of a variable, so decltype(x) is int. But wrapping the name x in parentheses—“(x)”—yields an expression more complicated than a name. Being a name, x is an lvalue, and C++ defines the expression (x) to be an lvalue, too. decltype((x)) is therefore int&. Putting parentheses around a name can change the type that decltype reports for it!

谁能告诉我变量 say x 的输出,其中 decltype(x) 和 decltype((xx)) 的输出类型不同?我需要一个明确显示输出差异的示例。

对此表示赞赏。谢谢。

最佳答案

如果你声明一个类型为decltype((x))的变量,它就是一个引用。查看差异的最简单方法可能是这样的:

int x = 0;
decltype(x) copy = x; // creates an int which is a copy of x
decltype((x)) ref = x; // creates a reference to x

ref = 7; // changes x
copy = 99; // does not change x

std::cout << x << '\n'; // prints 7
std::cout << copy << '\n'; // prints 99
std::cout << ref << '\n'; // prints 7

至于何时使用 decltype((x)),我不敢说永远不会,但我可以说我从来没有理由在我自己的代码中这样做。

关于c++需要清晰的示例来显示 decltype(x) 和 decltype((x)) 之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33073256/

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