C11中_Generic的语法和示例用法

时间:2012-03-21 12:11:35

标签: c generics c11

我听说C11添加了泛型。我已经google了一下,查看了一些文章,了解到有一个新的关键字(_Generic)和所有。但我似乎无法把握住这一切。

它是类似C#中的泛型还是C ++中的模板?任何人都可以给我一个关于泛型的C11定义,它的语法和一个简单的示例用法示例的简要说明吗?

3 个答案:

答案 0 :(得分:77)

The best example I have seen激发了以下(可运行的)示例,它解开了各种奇怪的可能性,用于破解内省......

#include <stdio.h>
#include <stddef.h>
#include <stdint.h>

#define typename(x) _Generic((x),        /* Get the name of a type */             \
                                                                                  \
        _Bool: "_Bool",                  unsigned char: "unsigned char",          \
         char: "char",                     signed char: "signed char",            \
    short int: "short int",         unsigned short int: "unsigned short int",     \
          int: "int",                     unsigned int: "unsigned int",           \
     long int: "long int",           unsigned long int: "unsigned long int",      \
long long int: "long long int", unsigned long long int: "unsigned long long int", \
        float: "float",                         double: "double",                 \
  long double: "long double",                   char *: "pointer to char",        \
       void *: "pointer to void",                int *: "pointer to int",         \
      default: "other")

#define fmt "%20s is '%s'\n"
int main() {

  size_t s; ptrdiff_t p; intmax_t i; int ai[3] = {0}; return printf( fmt fmt fmt fmt fmt fmt fmt fmt,

     "size_t", typename(s),               "ptrdiff_t", typename(p),     
   "intmax_t", typename(i),      "character constant", typename('0'),
 "0x7FFFFFFF", typename(0x7FFFFFFF),     "0xFFFFFFFF", typename(0xFFFFFFFF),
"0x7FFFFFFFU", typename(0x7FFFFFFFU),  "array of int", typename(ai));
}
                 ╔═══════════════╗ 
═════════════════╣ Amazeballs... ╠═════════════════════════════════════
                 ╚═══════════════╝ 
            size_t is 'unsigned long int'
         ptrdiff_t is 'long int'
          intmax_t is 'long int'
character constant is 'int'
        0x7FFFFFFF is 'int'
        0xFFFFFFFF is 'unsigned int'
       0x7FFFFFFFU is 'unsigned int'
      array of int is 'other'

答案 1 :(得分:44)

This是一个非常好的介绍。这是概述:

  

使用新关键字实现通用选择:_Generic。语法类似于a   类型的简单switch语句:_Generic( 'a', char: 1, int: 2, long: 3, default: 0)   计算结果为2(字符常量是C中的整数)。

基本上它就像一种switch,其中标签是根据第一个表达式(上面的'a')的类型进行测试的类型名称。结果成为评估_Generic()

的结果

答案 2 :(得分:6)

我使用clion 1.2.4,clion现在不支持c11,所以我在c99中使用以下代码而不是_Generic

#include <stdio.h>

int main(int argc, char **argv) {
    char *s;
    if (__builtin_types_compatible_p(__typeof__(s), long)) {
        puts("long");
    } else if (__builtin_types_compatible_p(__typeof__(s), char*)) {
        puts("str");
    }
    return (0);
};