C 中的伪泛型 [英] Pseudo-generics in C

查看:24
本文介绍了C 中的伪泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现一些方法来处理不同类型的数字数组.通常,我会使用泛型来完成这项工作,但由于 C 不提供它们,我现在尝试使用宏来模拟它们.

I need to implement some methods that do stuff with different kinds of number arrays. Usually, I'd use generics for that job, but as C doesn't provide them, I'm now trying to emulate them using macros.

这是我正在尝试做的一个例子:

Here's an example of what I'm trying to do:

#ifndef TYPE
#define TYPE int
#endif

TYPE get_minimum_##TYPE (TYPE * nums, int len){
    TYPE min = nums[0];

    for (int i = 1; i < len; i++) {
        if (nums[i] < min) {
            min = nums[i];
        }
    }

    return min;
}

然而,这不会编译.叮当错误信息:

However, this won't compile. The clang error message:

错误:应为';'在顶级声明符之后

error: expected ';' after top level declarator

有没有办法在 C 中做到这一点?还是我需要手动为每种类型实现它?

Is there any way to do this in C? Or do I need implement this for every type by hand?

推荐答案

你可以在头文件中做这样的事情:

You can do something like this in a header file:

//
// generic.h
//

#define TOKENPASTE(x, y) x ## y

#define GET_MINIMUM(T) TOKENPASTE(get_minimum_, T)

TYPE GET_MINIMUM (TYPE) (TYPE * nums, size_t len){
    TYPE min = nums[0];

    for (size_t i = 1; i < len; i++) {
        if (nums[i] < min) {
            min = nums[i];
        }
    }

    return min;
}

然后 #include 将它放在每个所需类型的源文件中,例如:

and then #include it in a source file for each required type, e.g.:

//
// generic.c
//

#define TYPE int
#include "generic.h"
#undef TYPE

#define TYPE float
#include "generic.h"
#undef TYPE

您可以通过预处理器运行它来测试它:

You can test this by running it through the preprocessor:

$ gcc -E generic.c 

int get_minimum_int (int * nums, size_t len){
    int min = nums[0];

    for (size_t i = 1; i < len; i++) {
        if (nums[i] < min) {
            min = nums[i];
        }
    }

    return min;
}

float get_minimum_float (float * nums, size_t len){
    float min = nums[0];

    for (size_t i = 1; i < len; i++) {
        if (nums[i] < min) {
            min = nums[i];
        }
    }

    return min;
}

这篇关于C 中的伪泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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