3

データへのポインタを格納するリンク リストを C (C++ ではない) で実装しました。関数の複数の宣言を (タイプ セーフを提供するために) したいのですが、それぞれを同じ定義にリンクさせます (異なるデータ型へのポインター間に実際の違いがないため、同じコードを使用するとスペースが削減されるため)。

これを達成する方法(またはそれを行うためのより良い方法)に関するアイデアはありますか?ポータブル ソリューションが最適であることは明らかですが、GCC で動作するものが本当に必要なだけです。

4

3 に答える 3

1

void*関数プロトタイプの typedef を使用し、一般的なソリューション ( s を扱う) を特定のプロトタイプにキャストすることで、これを達成できると思います。すべてのポインターが同じサイズになるため、これはコンパイルしても安全です。

次の例を検討してください。

do_something.h:

typedef void (*do_something_with_int_t)(int *i);
extern do_something_with_int_t do_something_with_int;

typedef void (*do_something_with_string_t)(char *s);
extern do_something_with_string_t do_something_with_string;

do_something.c

#include "do_something.h"

void do_something_generic(void* p) {
    // Do something generic with p
}


do_something_with_int_t do_something_with_int =
    (do_something_with_int_t)do_something_generic;

do_something_with_string_t do_something_with_string =
    (do_something_with_string_t)do_something_generic;

本当にデータ型にとらわれない限りdo_something_generic(つまり、何を指すかは問題ではありません)、これで問題ありません。p

于 2013-05-23T02:21:34.700 に答える
0
#include <stdio.h>
struct common_type {
    int type;
};

struct type1 {
    int type;
    int value;
};

struct type2 {
    int type;
    char* p;
};

int func(void *para) {
    switch (((struct common_type*)para)->type) {
        case 1:
            printf("type1,value:%d\n",((struct type1*)para)->value);
            break;
        case 2:
            printf("type2,content:%s\n",((struct type2*)para)->p);
            break;
    }
}

int main() {
    char *s = "word";
    struct type1 t1 = {1,1};
    struct type2 t2;
    t2.type = 2;
    t2.p = s;
    func((void*)&t1);   
    func((void*)&t2);
}
于 2013-05-23T01:52:47.727 に答える