有没有办法在C中实现函数重载?我正在寻找简单的函数被重载像
foo (int a)
foo (char b)
foo (float c , int d)
我认为没有直接的方法;我在寻找变通办法,如果有的话。
有没有办法在C中实现函数重载?我正在寻找简单的函数被重载像
foo (int a)
foo (char b)
foo (float c , int d)
我认为没有直接的方法;我在寻找变通办法,如果有的话。
当前回答
就你的意思来说——不,你不能。
你可以像这样声明一个va_arg函数
Void my_func(char*格式,…);
,但是您需要在第一个参数中传递一些关于变量数量及其类型的信息-就像printf()所做的那样。
其他回答
就你的意思来说——不,你不能。
你可以像这样声明一个va_arg函数
Void my_func(char*格式,…);
,但是您需要在第一个参数中传递一些关于变量数量及其类型的信息-就像printf()所做的那样。
你不能只使用c++而不使用除这个以外的所有其他c++特性吗?
如果仍然没有严格的C,那么我会推荐变进函数代替。
下面是我发现的演示C语言中函数重载的最清晰、最简洁的例子:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int addi(int a, int b) {
return a + b;
}
char *adds(char *a, char *b) {
char *res = malloc(strlen(a) + strlen(b) + 1);
strcpy(res, a);
strcat(res, b);
return res;
}
#define add(a, b) _Generic(a, int: addi, char*: adds)(a, b)
int main(void) {
int a = 1, b = 2;
printf("%d\n", add(a, b)); // 3
char *c = "hello ", *d = "world";
printf("%s\n", add(c, d)); // hello world
return 0;
}
https://gist.github.com/barosl/e0af4a92b2b8cabd05a7
如前所述,c不支持重载。解决这个问题的常用方法是让函数接受带标签的联合。这是通过一个struct形参实现的,其中struct本身由某种类型指示符(例如枚举)和不同类型值的并集组成。例子:
#include <stdio.h>
typedef enum {
T_INT,
T_FLOAT,
T_CHAR,
} my_type;
typedef struct {
my_type type;
union {
int a;
float b;
char c;
} my_union;
} my_struct;
void set_overload (my_struct *whatever)
{
switch (whatever->type)
{
case T_INT:
whatever->my_union.a = 1;
break;
case T_FLOAT:
whatever->my_union.b = 2.0;
break;
case T_CHAR:
whatever->my_union.c = '3';
}
}
void printf_overload (my_struct *whatever) {
switch (whatever->type)
{
case T_INT:
printf("%d\n", whatever->my_union.a);
break;
case T_FLOAT:
printf("%f\n", whatever->my_union.b);
break;
case T_CHAR:
printf("%c\n", whatever->my_union.c);
break;
}
}
int main (int argc, char* argv[])
{
my_struct s;
s.type=T_INT;
set_overload(&s);
printf_overload(&s);
s.type=T_FLOAT;
set_overload(&s);
printf_overload(&s);
s.type=T_CHAR;
set_overload(&s);
printf_overload(&s);
}
这可能没有任何帮助,但如果你使用clang,你可以使用overloadable属性-即使在编译为C时也可以
http://clang.llvm.org/docs/AttributeReference.html#overloadable
头
extern void DecodeImageNow(CGImageRef image, CGContextRef usingContext) __attribute__((overloadable));
extern void DecodeImageNow(CGImageRef image) __attribute__((overloadable));
实现
void __attribute__((overloadable)) DecodeImageNow(CGImageRef image, CGContextRef usingContext { ... }
void __attribute__((overloadable)) DecodeImageNow(CGImageRef image) { ... }