我一直在用__auto_type
在 C 中使用了一段时间,我想知道它是否与 auto
有任何不同在 C++ 中。它们的实现方式不同吗?
我试过搜索这个,但它没有产生任何结果,因为搜索 C 中的 __auto_type 返回关于 auto
的文章在 C++ 中。感觉就像一个被遗忘的关键字。
最佳答案
正如 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; })
如您所见,它是 不是 与
auto
完全相同在 C++ 中,因为auto
在 C++ 中可用于声明多个变量,如 auto i = 0, *p = &i;
auto f();
或 void f(auto);
也不能代替
auto
在 decltype(auto)
的情况下,或者像 const auto& i = expr;
一样使用因为在 C 中没有这样的功能然而后来 Clang 采用了这个关键字和 在 C++ 中也支持它 它在哪里与
auto
完全相同它甚至可以用于 C++98This implementation differs from GCC's in also supporting
__auto_type
in C++, treating it the same asauto
. 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
orauto
depending on the language, but then C++ pre-11 is broken).
Demo for Clang++
Objective C 也支持它
关于c++ - auto 和 __auto_type 之间有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64846957/