• C/C++: 自动类型推导,typeof/__auto_type/auto


    简介

    在C++里又关键字auto,可以自动推导出表达式的类型;从写法上来看,C++的auto更为方便。其实这些个变量(表达式)的类型编译器是知道的,就是怎么根据当前变量的类型定义一个新的变量,具有相同的类型。实现的功能都是一样的。
    C++里的auto;
    C里的typeof,GCC提供的__auto_type;
    都是完成这一功能的关键字。

    举例

    __auto_type

    这个和auto的作用完全一致,就应用来说是实现了使用统一的方式。而且使用__auto_type相对于typeof的优势是:

    1. 很明显,就是变量只在表达式里出现一次;这个就是使用方便的情况。减小了宏展开的大小。
    2. If the argument to the macro has variably modified type, it is evaluated only once when using __auto_type, but twice if typeof is used.
    #define atomic_store_explicit(PTR, VAL, MO)				\
      __extension__								\
      ({									\
        __auto_type __atomic_store_ptr = (PTR);				\
        //这里是重新创建一个PTR类型的变量
        __typeof__ (*__atomic_store_ptr) __atomic_store_tmp = (VAL);	\
        //这里是将指针解引用,就是类型的原始类型,然后创建临时变量
        __atomic_store (__atomic_store_ptr, &__atomic_store_tmp, (MO));	\
        //最后使用到这个新键的指针变量,及临时变量做操作。
      })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    上面这个例子,明显还是用到了typeof的宏;只是对于ansi标准或者其他std标准,里面没有typeof关键字。所以在使用GNU C扩展功能时,可能会出现一些问题。或者一般性目的的头文件,需要兼容这些标准的程序。但是asm, typeof和inline不可用,所以只能使用替换方案,这就是__typeof__出现的原因。

    问题出来了,这里为什么两个都是用到了?有什么特殊的原因吗?

    typeof 、、 typeof (两边有两个下划线)功能相同

    这个使用上略显麻烦。

    #define max(a,b) \
    ({ typeof (a) _a = (a); \
    typeof (b) _b = (b); \
    _a > _b ? _a : _b; })
    
    • 1
    • 2
    • 3
    • 4

    https://mzhan017.blog.csdn.net/article/details/128415988

    _auto_type

    这个和C++的auto类似,都有关键字auto,用法也类似。

    #define max(a,b) \
    ({ __auto_type _a = (a); \
    __auto_type _b = (b); \
    _a > _b ? _a : _b; })
    
    • 1
    • 2
    • 3
    • 4

    auto

    自动类型推导。

    typeof 又一例

    /* Are two types/vars the same type (ignoring qualifiers)? */
    #ifndef __same_type
    # define __same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))
    #endif
    
    • 1
    • 2
    • 3
    • 4
  • 相关阅读:
    【C/C++】C语言runtime调用技术
    python爬虫基础-request请求头
    单例模式——C++版本
    派克液压油泵PVP3336R2M
    金九银十面试跳槽季;你准备好了吗?
    Vue3 从入门到放弃 (第五篇.组件事件与v-model使用)
    Qt开发学习笔记02
    8.9模拟赛总结
    设计模式之单例模式
    【Flink实战】Flink对接Kafka Connetor使用docker部署kafka
  • 原文地址:https://blog.csdn.net/qq_36428903/article/details/127709777