如何编写一个方法来确定运行时的typedef类型?

时间:2010-12-20 10:10:01

标签: visual-c++ typedef

我有一个二叉搜索树,我想用不同的类型实现。二进制搜索树是模板化的,使用以下语句确定:

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

通常情况下,我只是将desiredType更改为字符串树的字符串,但是如果我还要创建一个整数树呢?我想我需要在运行时创建一个确定typdef类型的方法但我不知道开始因为desiredType可以是各种变量对象类型。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

从一行很难说,但看起来你可以使用C预处理器命令 喜欢

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

... <code>

#define  desiredType saveDesiredType  // restore previous setting

但是,我认为你只能在模块中定义一个特定的typedef(目标文件.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-&gt; 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. */

(看起来像是工作,不是吗?)