[yc]伪typeof

[yc]伪typeof


发信人: shifan (学习浮云技术), 板面: C++
标  题: 伪typeof
发信站: 飘渺水云间 (Tue Dec 19 16:38:45 2006), 转信
 1  /*
 2  用标准C++实现typeof是不可能的
 3  这个是我写的一个approached typeof
 4  所有需要被静态反射出来的类型必须先用DECL_TYPE注册
 5  模板如果仅仅带有1个参数可以用DECL_TEMPLATE_1注册
 6  多个参数的模板还不支持。。
 7  主要是没想好编码
 8 
 9  总共能注册64个类型
10  可以通过MAX_TYPE_NUMBER设置
11 
12  支持的模板嵌套层数大约为32 / log2(MAX_TYPE_NUMBER)
13  MAX_TYPE_NUMBER必须为2的整次数幂
14  */
15  namespace  my_typeof
16  {
17 
18     const   int  MAX_TYPE_NUMBER  =   64 ;
19 
20    template  < int  N >
21     struct  dummy
22    {
23       int  a[N];
24    };
25 
26 
27    template  < int  N, typename Arg1 >
28     struct  select_by_number_1;
29 
30    template  < int  N >
31     struct  select_by_number
32    {
33      typedef typename select_by_number_1 < %  MAX_TYPE_NUMBER, typename
34  select_by_number < /  MAX_TYPE_NUMBER > ::type > ::type type;
35    };
36 
37 
38    template  < typename T >
39     struct  number_of
40    {
41       static   const   int  v  =   sizeof (generic_f( * (T * ) 0 ))  /   sizeof ( int );
42    };
43 
44 
45  #define  DECL_TYPE(T, N) \
46     namespace  my_typeof{  \
47    template <> \
48     struct  select_by_number < N >  \
49    {\
50      typedef T type;\
51    };\
52    dummy  < N >  generic_f( const  T & );}
53 
54 
55  #define  DECL_TEMPLATE_1(T, N) \
56     namespace  my_typeof{        \
57    template < typename Arg1 > \
58     struct  select_by_number_1 < N, Arg1 > \
59    {\
60      typedef T < Arg1 >  type;\
61    };\
62    template  < typename Arg1 > \
63    dummy < +  number_of < Arg1 > ::v  *  MAX_TYPE_NUMBER  >  generic_f( const  T < Arg1 >& );}
64 
65 
66 
67  #define  TYPE_OF(x) my_typeof::select_by_number<sizeof(my_typeof::generic_f(x)) /
68  sizeof  ( int ) > ::type
69 
70  }
71 
72 
73  // sample
74  #include  < iostream >
75  #include  < vector >
76  #include  < list >
77 
78 
79  DECL_TYPE( int 1 );
80  DECL_TEMPLATE_1(std::vector,  2 );
81  DECL_TEMPLATE_1(std::list,  3 );
82  DECL_TYPE( double 4 )
83 
84  using   namespace  std;
85  int  main( int char * [])
86  {
87    vector < list < vector < list < double >   >   >   >  v1;
88    TYPE_OF(v1) v2;
89    v1  =  v2;
90     return   0 ;
91  }
92 
93 


--
You well 撒法!You well all 撒法!

※ 内容修改:·shifan 于 Dec 21 14:21:57 修改本文内容·[FROM: shifan]
※ 来源:·飘渺水云间 freecity.cn·[FROM: shifan]

你可能感兴趣的:([yc]伪typeof)