【问题标题】:Creating C "Template" function创建 C“模板”函数
【发布时间】:2020-06-02 15:37:36
【问题描述】:

我目前正在做一个需要我使用一些链表的项目。

我已经习惯了,但我真的不喜欢我需要复制我的代码这一事实。 这就是我的意思:

struct A {
    struct A *prev;
    struct A *next;

    int i;
}


struct B {
    struct B *prev;
    struct B *next;

    char *str;
}

如果我想创建一个将元素添加到我喜欢的列表中的函数,我需要执行以下操作:

void add_A_element(struct A *list, struct A *new_element) { [...] }

void add_B_element(struct B *list, struct B *new_element) { [...] }

这是我的问题,有没有办法让我的所有结构都只有一个功能?

我想知道是否可以使用其他结构,例如:

struct template {
    struct template *prev;
    struct template *next;
}

然后添加我的元素的函数如下所示:

void add_element(void *list, void *new_element)
{
    struct template tmp_list = (struct template *)list;
    struct template tmp_new_element = (struct template *)new_element;

    for (struct template tmp = tmp_list; tmp != NULL; tmp = tmp->next) {
        if (tmp->next == NULL) {
            tmp->next = tmp_new_element;
            tmp_new_element->prev = tmp;
            break;
        }
    }
    return;
}

因为我们修改了相同的内存空间,我想这可以工作,但我认为可能会发生一些意想不到的问题。
我想知道 C 中是否存在看起来更像 C++ 模板的东西。

任何帮助将不胜感激。谢谢

编辑:我设法做到了。我仍在计划添加一些东西,例如 fifo/lifo 队列,但您已经可以在 my Github

上获得它

【问题讨论】:

    标签: c pointers templates structure


    【解决方案1】:

    如果您想看一下,我有完整的 C 语言模板(宏)解决方案,最后链接。同时,让我解释一下如何解决这个问题:

    你应该使用container_of 策略抽象地遍历一个链表。

    struct linked_list_head
    {
        struct linked_list_head * next;
        struct linked_list_head * prev;
    };
    
    struct my_type {
     ...
     struct linked_list_head head;
    }
    

    那么获取下一个的代码是

    struct linked_list_head next(struct linked_list_head * current) {
      return current->next;
    }
    
    struct my_type next = container_of(next(&current.head), struct my_type, head));
    
    

    什么是container_of 宏?

    Understanding container_of macro in the Linux kernel

    如果您想查看使用实施模板的完整解决方案,我有一个免费使用(风险自负)的解决方案:

    图书馆:https://github.com/flplv/fl-lib/blob/master/headers/linked_list.h

    用法:https://github.com/flplv/fl-lib/blob/master/tests/test_linked_list.cpp

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-01
      • 2021-05-29
      • 2012-11-09
      • 1970-01-01
      • 1970-01-01
      • 2020-01-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多