發信人: 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<N % MAX_TYPE_NUMBER, typename
34 select_by_number<N / 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<N + 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]
posted on 2006-12-21 14:29
shifan3 閱讀(2644)
評論(8) 編輯 收藏 引用 所屬分類:
template 、
C++