开发者

How can I write a method to determine the typedef type at runtime?

I have a binary search tree that I want to implement with different types. The binary search tree is templated开发者_JAVA技巧 and is determined using the following statement:

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

Normally I would just change the desiredType to string for a tree of strings but what if I want to also make a tree of integers? I'm thinking I need to make a method for determining the typdef type at runtime but I don't know to begin because desiredType can be a variety of variable object types. Any ideas?


It is hard to tell from one line, but it looks like you could use a C Preprocessor command like

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

... <code>

#define  desiredType saveDesiredType  // restore previous setting

however, I think you may only define a particular typedef once in a module (object file .o).

The ONLY way I know to create workable tree structures of variable types in C is to go to an all pointer manipulation model, or add the type as an extra parameter to the tree functions, and do ALL the pointer math for the different sizes of the types.
A slightly more object centric approach woul be to encapsulate your data in a tree_node struct with type data.

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

In your code you must switch on node->dtype and work only with the variable of that type.

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

(seems like work, doesn't it?)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜