C11 中_Generic 的语法和示例用法 [英] Syntax and Sample Usage of _Generic in C11

查看:55
本文介绍了C11 中_Generic 的语法和示例用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我听说 C11 添加了泛型.我用谷歌搜索了一下,看了一些文章,知道有一个新关键字( _Generic )等等.但我似乎无法全部掌握.

I heard C11 added generics. I've googled a bit, looked at some articles, understood there's a new keyword ( _Generic ) and all. But I can't seem to grasp it all.

它是否类似于 C# 中的泛型或 C++ 中的模板?谁能给我简要解释一下泛型的 C11 定义、它的语法和一个简单的示例用法示例?

Is it something like the generics in C# or templates in C++? Can anyone give me a brief explanation of the C11 definition of generics, its syntax and a simple sample usage example?

推荐答案

这是一个很好的介绍.概览如下:

This is a pretty good introduction. Here's the Overview:

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

Generic selection is implemented with a new keyword: _Generic. The syntax is similar to a simple switch statement for types:_Generic( 'a', char: 1, int: 2, long: 3, default: 0) evaluates to 2 (character constants are ints in C).

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

Basically it works like a kind of switch, where the labels are type names which are tested against the type of the first expression (the 'a' above). The result becomes the result of evaluating the _Generic().

这篇关于C11 中_Generic 的语法和示例用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆