什么时候应该使用decltype(x)而不是auto来声明变量的类型? [英] When should I use decltype(x) instead of auto to declare the type of a variable?

查看:95
本文介绍了什么时候应该使用decltype(x)而不是auto来声明变量的类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到 decltype(x)在宏中使用,其中 x 是变量名,因为对象的类型

I see decltype(x) used inside macros where x is a variable name because the type of the object isn't known inside macros.

例如:

decltype(x) y = expr;

我可以轻松地使用 auto decltype 的值。那么在什么情况下需要 decltype 来进行变量类型声明而不是 auto

I could just have easily use auto instead of decltype. So what are those situations where decltype is needed for a variable type declaration instead of auto?

推荐答案

当所需的 y 类型为:


  • expr 类型不同(或可能不同)。如果相同,则 auto 会更简洁。

  • 对于 auto& auto 可以表示的 expr 类型的其他修改。

  • different (or potentially different) from the type of expr. If it was the same then auto would be more concise.
  • similarly for auto & or other modifications of the type of expr that auto can express.

和以下其中一项:


  • 取决于周围的事物代码(即不总是相同的类型),并且很难使用类型特征或类似特征编写。这将倾向于在模板代码中发生。可以使用一种类型特征来从模板参数中获取所需的类型,但是再次使用 decltype 可能不会使您定义一个。

  • 总是相同的类型(或以易于使用现有类型特征或类似形式表示的方式依赖于模板参数),但是该类型写起来很费劲,并且存在

  • dependent on something in the surrounding code (i.e. not always the same type) and difficult to write using type traits or similar. This will tend to happen in template code. There might be a type trait that you can use to get the required type from the template parameters, but then again there might not so a use of decltype would save you defining one.
  • always the same type, (or dependent on template parameters in a way that is easy to express using existing type traits or similar) but the type is very long-winded to write and there is a much shorter and clear expression you can use instead.

因此例如替换 std :: iterator_traits< RandomAccessIterator> ; :: value_type decltype(* it)可能是一个胜利,尽管 auto 确实会处理这类情况。

So for example replacing std::iterator_traits<RandomAccessIterator>::value_type with decltype(*it) might well be a win, although auto does often handle such cases.

主观判断是在困难是什么,困难是什么和清楚是什么的时候输入的,但是无论您如何在特定情况下做出这些判断,程序规则都可以相同。

Subjective judgements enter at the point of "what is difficult", "what is long-winded" and "what is clear", but the rules of procedure can be the same regardless of how you make those judgements in specific cases.

这篇关于什么时候应该使用decltype(x)而不是auto来声明变量的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆