c++ - auto 和 __auto_type 之间有什么区别吗?

标签 c++ c keyword type-inference auto

我一直在用__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; })

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


如您所见,它是 不是 auto 完全相同在 C++ 中,因为
  • 它只能用于声明单个变量,而 auto在 C++ 中可用于声明多个变量,如 auto i = 0, *p = &i;
  • 它不能出现在函数(或 lambda)的返回类型或参数中,例如 auto f();void f(auto);

  • 也不能代替autodecltype(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 也支持它

    关于c++ - auto 和 __auto_type 之间有什么区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64846957/

    相关文章:

    c++ - 从 cin 中选择下一行

    python - Swig 和多维数组

    c++ - 在 C/C++ 中将天文数字大的数字转换为人类可读的形式

    c++ - "typename"和 "template"关键字 : are they really necessary?

    c# - C#中的Register关键字是什么

    c++ - 路径树到树结构

    c++ - 从 OpenCV Mat 中删除列

    c++ - 使用 std::shared_ptr 和 std::thread 的编译器错误

    c - 修复 UART 溢出

    django - 如何将过滤器关键字上的字符串传递给 Django 对象模型?