c - 使用 C 的直接多态性
问题描述
是否可以使用 C 来制作多态函数,而我们不必在主函数中使用任何类或 OOP 类型的函数调用?
就像,我想做一个函数来返回两个整数或字符或字符串中的最小值。我只想调用function_name(variable1, variable2)
主函数中的函数。
使用 C++ 模板很容易做到这一点,但有没有办法用 C 来做到这一点?我已经仔细阅读了所有与“C 多态性”相关的问题和答案,但找不到任何线索。
解决方案
有时a#define
可以为所欲为。
但它使用起来既困难又复杂。以linux中的max宏为例:
从 linux 5.12-rc2:/include/linux/minmax.h
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef _LINUX_MINMAX_H
#define _LINUX_MINMAX_H
/*
* min()/max()/clamp() macros must accomplish three things:
*
* - avoid multiple evaluations of the arguments (so side-effects like
* "x++" happen only once) when non-constant.
* - perform strict type-checking (to generate warnings instead of
* nasty runtime surprises). See the "unnecessary" pointer comparison
* in __typecheck().
* - retain result as a constant expressions when called with only
* constant expressions (to avoid tripping VLA warnings in stack
* allocation usage).
*/
#define __typecheck(x, y) \
(!!(sizeof((typeof(x) *)1 == (typeof(y) *)1)))
/*
* This returns a constant expression while determining if an argument is
* a constant expression, most importantly without evaluating the argument.
* Glory to Martin Uecker <Martin.Uecker@med.uni-goettingen.de>
*/
#define __is_constexpr(x) \
(sizeof(int) == sizeof(*(8 ? ((void *)((long)(x) * 0l)) : (int *)8)))
#define __no_side_effects(x, y) \
(__is_constexpr(x) && __is_constexpr(y))
#define __safe_cmp(x, y) \
(__typecheck(x, y) && __no_side_effects(x, y))
#define __cmp(x, y, op) ((x) op (y) ? (x) : (y))
#define __cmp_once(x, y, unique_x, unique_y, op) ({ \
typeof(x) unique_x = (x); \
typeof(y) unique_y = (y); \
__cmp(unique_x, unique_y, op); })
#define __careful_cmp(x, y, op) \
__builtin_choose_expr(__safe_cmp(x, y), \
__cmp(x, y, op), \
__cmp_once(x, y, __UNIQUE_ID(__x), __UNIQUE_ID(__y), op))
/**
* min - return minimum of two values of the same or compatible types
* @x: first value
* @y: second value
*/
#define min(x, y) __careful_cmp(x, y, <)
/**
* max - return maximum of two values of the same or compatible types
* @x: first value
* @y: second value
*/
#define max(x, y) __careful_cmp(x, y, >)
/**
* min3 - return minimum of three values
* @x: first value
* @y: second value
* @z: third value
*/
#define min3(x, y, z) min((typeof(x))min(x, y), z)
/**
* max3 - return maximum of three values
* @x: first value
* @y: second value
* @z: third value
*/
#define max3(x, y, z) max((typeof(x))max(x, y), z)
C 语言本身没有适当的方法来处理这个问题。
对于轻量级项目,您可以简单地为每种类型实现这样的功能:
int min(int a, int b) {...}
short min(short a, short b) {...}
float min(float a, float b) {...}
...
推荐阅读
- mobile - 应用程序中的卡支付,用于点对点支付
- c++ - 问题初始化 SimpleBlobDetector 的参数
- python - 张量流估计器的准确性和损失为零
- amazon-web-services - 如何使用 importValue 并加入 Cloudformation
- linux - 如何防止 docker 在错误时停止/删除容器
- c# - 动态创建的用户控件内的事件不会触发
- ruby - Ruby - 按列对 CSV 文件中的数据进行分组
- sails.js - 在 Sail.js 的控制器上创建用户定义的角色和动态应用 ACL 的最佳方法是什么?
- android - 在 libGDX 中缩放相机不保存尺寸
- android - Kotlin 中的图像共享意图问题