Featured post
visual c++ - How can I write a method to determine the typedef type at runtime? -
i have binary search tree want implement different types. binary search tree templated , determined using following statement:
typedef desiredtype treeitemtype; // desired type of tree items i.e. string, int, person
normally change desiredtype string tree of strings if want make tree of integers? i'm thinking need make method determining typdef type @ runtime don't know begin because desiredtype can variety of variable object types. ideas?
it hard tell 1 line, looks use c preprocessor command
#define savedesiredtype desiredtype // save previous setting #define desiredtype char* // change type ... <code> #define desiredtype savedesiredtype // restore previous setting
however, think may define particular typedef once in module (object file .o).
the way know create workable tree structures of variable types in c go pointer manipulation model, or add type parameter tree functions, , pointer math different sizes of types.
more object centric approach woul encapsulate data in tree_node struct type data.
typedef enum d_type { anint , afloat, adouble, achar, astring, other} datatype; typedef struct t_node{ datatype dtype; union { // union 1 of following types, , one. int i; // size of union size of largest type. float f; double d; char c; char* string; } // union unnamed , have name. } tree_node; typedef tree_node* treeitem; //pass reference
in code must switch on node->dtype , work variable of type.
void tree_add (tree t, treeitem item) { int i; float f; double d; char c; char* s; switch (item->dtype){ case anint: = 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 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 time programmers come aid of computers."; /* oops! error. undefined behavior double d? (this might go through without being detected -- depending on compiler ) ti->dtype not changed either code break. */
(seems work, doesn't it?)
- Get link
- X
- Other Apps
Comments
Post a Comment