auto 和 __auto_type 有什么区别吗?

Is there any difference between auto and __auto_type?

我在 C 中使用 __auto_type 有一段时间了,我想知道它与 C++ 中的 auto 是否有任何不同。它们的实现方式不同吗?

我试过搜索这个,但没有得到任何结果,因为在 C[=21 中搜索 __auto_type =] returns 关于 C++ 中 auto 的文章。感觉像是忘记了关键字。

正如 StoryTeller 评论的那样,它是 C 模式下的 GCC 扩展。它在 C++ 中不起作用

In GNU C, but not GNU C++, you may also declare the type of a variable as __auto_type. In that case, the declaration must declare only one variable, whose declarator must just be an identifier, the declaration must be initialized, and the type of the variable is determined by the initializer; the name of the variable is not in scope until after the initializer. (In C++, you should use C++11 auto for this purpose.) Using __auto_type, the “maximum” macro above could be written as:

   #define max(a,b) \
     ({ __auto_type _a = (a); \
     __auto_type _b = (b); \
     _a > _b ? _a : _b; })

https://gcc.gnu.org/onlinedocs/gcc/Typeof.html

如你所见,它不是与C++中的auto完全一样,因为

  • 只能用于声明单个变量,而C++中的auto可以用于声明多个变量,如auto i = 0, *p = &i;
  • 它不能出现在函数(或 lambda)的 return 类型或参数中,例如 auto f();void f(auto);

它不能在 decltype(auto) 的情况下也替换 auto,或者像 const auto& i = expr; 一样使用,因为 C

中没有这样的功能

不过后来 Clang 采用了这个关键字,在 C++ 中也支持它 auto 完全相同并且它甚至可以用于 C++98

This implementation differs from GCC's in also supporting __auto_type in C++, treating it the same as auto. I don't see any good reason not to, because otherwise headers intended to be used from both languages can't use it (you could use a define that expands to __auto_type or auto depending on the language, but then C++ pre-11 is broken).

Add support for GCC's '__auto_type' extension.

Demo for Clang++

Objective C

也支持它