2010-12-20 9 views
1

私は異なるタイプで実装したいバイナリ検索ツリーを持っています。バイナリ検索ツリーはテンプレートで、次のステートメントを使用して決定されます。実行時にtypedef型を判別するメソッドを書くにはどうすればよいですか?

typedef desiredType TreeItemType; // desired type of tree items i.e. string, int, Person 

通常、私は文字列だけの木のための文字列にdesiredTypeを変更するだろうが、私はまた、整数のツリーを作りたい場合はどう?私は実行時にtypdef型を決定するメソッドを作る必要があると思っていますが、desiredTypeはさまざまな可変オブジェクト型になる可能性があるため、開始するのはわかりません。何か案は?

+0

あなたは、整数の文字列とはどういう意味ですか?なぜテンプレートを使用するのが不十分な解決策ですか? – x13n

+0

私は整数の木を意味しました。テンプレートで十分です。私はどのようにコードを複製せずに異なるタイプの2つのツリーを作成するか分からない。 – David

答えて

0

しかし、私はオブジェクト(あなただけのモジュールに一度、特定の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. */ 

(それは、仕事好きではないようだ?)

関連する問題