十进制vs自动

编程入门 行业动态 更新时间:2024-10-28 06:22:06
本文介绍了十进制vs自动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

据我了解, decltype 和 auto 都将试图弄清某种事物的类型.

As I understand it, both decltype and auto will attempt to figure out what the type of something is.

如果我们定义:

int foo () { return 34; }

这两个声明都是合法的:

Then both declarations are legal:

auto x = foo(); cout << x << endl; decltype(foo()) y = 13; cout << y << endl;

能否请您告诉我 decltype 和 auto 之间的主要区别是什么?

Could you please tell me what the main difference between decltype and auto is?

推荐答案

decltype 给出传递给它的表达式的声明的类型. auto 的作用与模板类型推导相同.因此,例如,如果您有一个返回引用的函数,则 auto 仍将是一个值(您需要 auto& 来获取引用),但decltype 将恰好是返回值的类型.

decltype gives the declared type of the expression that is passed to it. auto does the same thing as template type deduction. So, for example, if you have a function that returns a reference, auto will still be a value (you need auto& to get a reference), but decltype will be exactly the type of the return value.

#include <iostream> int global{}; int& foo() { return global; } int main() { decltype(foo()) a = foo(); //a is an `int&` auto b = foo(); //b is an `int` b = 2; std::cout << "a: " << a << '\n'; //prints "a: 0" std::cout << "b: " << b << '\n'; //prints "b: 2" std::cout << "---\n"; decltype(foo()) c = foo(); //c is an `int&` c = 10; std::cout << "a: " << a << '\n'; //prints "a: 10" std::cout << "b: " << b << '\n'; //prints "b: 2" std::cout << "c: " << c << '\n'; //prints "c: 10" }

另请参阅DavidRodríguez关于仅在 auto 或 decltype 之一可能出现的位置的答案.

Also see David Rodríguez's answer about the places in which only one of auto or decltype are possible.

更多推荐

十进制vs自动

本文发布于:2023-06-02 07:32:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/440280.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:十进制

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!