2010-12-20 38 views
1

我有一個二叉搜索樹,我想用不同的類型實現。二叉搜索樹的模板,並使用下面的語句確定:如何編寫一個方法來確定運行時的typedef類型?

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

通常情況下,我只想改變desiredType到字符串樹串的,但如果我想也使整數的樹是什麼?我想我需要做一個方法來確定在運行時typdef類型,但我不知道開始,因爲desiredType可以是各種變量對象類型。有任何想法嗎?

+0

你是什麼意思的整數的字符串做?爲什麼使用模板不足以解決問題? – x13n 2010-12-20 10:13:36

+0

我的意思是一個整數樹。模板就足夠了。我不確定如何在不復制代碼的情況下創建兩種不同類型的樹。 – David 2010-12-20 10:17:25

回答

0

這是很難從一條線告訴,但它看起來像你可以使用C預處理命令 像

#define saveDesiredType desiredType // save previous setting 
#define desiredType char*     // change to type 

... <code> 

#define desiredType saveDesiredType // restore previous setting 
然而

,我想你可能只在一個模塊中,一旦確定了某一特定類型定義(對象文件.o)。

我知道在C中創建可變類型的可行樹結構的唯一方法是轉到全指針操作模型,或者將該類型作爲額外參數添加到樹函數中,然後執行所有指針數學運算不同大小的類型。
稍微更加以對象爲中心的方法將是將數據封裝在帶有類型數據的tree_node struct 中。

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. */ 

(似乎是工作,不是嗎?)

相關問題