しかし、私はオブジェクト(あなただけのモジュールに一度、特定のtypedefを定義するかもしれないと思うことが1行から伝えるのは難しいですが、
よう
#define saveDesiredType desiredType // save previous setting
#define desiredType char* // change to type
... <code>
#define desiredType saveDesiredType // restore previous setting
あなたがCプリプロセッサコマンドを使用することができますように見えますファイル.o)。
私は、Cで変数型の実行可能なツリー構造を作成する方法は、すべてのポインタ操作モデルに行くか、またはそのタイプをツリー関数に余分なパラメータとして追加することです。タイプの異なるサイズ。
型のデータを持つtree_node構造体 にデータをカプセル化するのは、オブジェクト中心のアプローチです。
typedef enum D_Type { ANINT , AFLOAT, ADOUBLE, ACHAR, ASTRING, OTHER} DATATYPE;
typedef struct t_node{
DATATYPE dtype;
union { // union is ONE of the following types, and Only one.
int i; // size of the union is the size of the largest type.
float f;
double d;
char c;
char* string;
} // this union is unnamed , but could have a name.
} Tree_Node;
typedef Tree_Node* TreeItem; //pass by reference
コードでは、node-> dtypeをオンにして、そのタイプの変数のみで作業する必要があります。
void tree_add (Tree T, TreeItem item)
{
int i;
float f;
double d;
char c;
char* s;
switch (item->dtype){
case ANINT:
i = item->i;
break;
case AFLOAT:
f = item->f;
break;
case ADFLOAT:
d = item->d;
break;
...
}//switch
...<code>
}//tree_add
double Pi = 3.141592653589793238;
TreeItem ti = (TreeItem) malloc (sizeof(Tree_Node)); // struct Must be allocated
ti->dtype = ADOUBLE;
ti->d = Pi;
ti->s = Pi; /* OOPS! error. (might go through without being detected -- depending on compiler) */
tree_add(atree , ti);
ti->s = "Now is the time for all good programmers to come the aid of their computers.";
/* OOPS! error. undefined behavior what about the double d?
(this might go through without being detected -- depending on compiler)
but ti->dtype was not changed either so code will break. */
(それは、仕事好きではないようだ?)
あなたは、整数の文字列とはどういう意味ですか?なぜテンプレートを使用するのが不十分な解決策ですか? – x13n
私は整数の木を意味しました。テンプレートで十分です。私はどのようにコードを複製せずに異なるタイプの2つのツリーを作成するか分からない。 – David