比这篇新的文章: main.cpp 测试程序
比这篇旧的文章: scientific_number.hpp

Type_Template_Level.h

语言: C++, 标签: 无  2008/08/26发布 2个月前更新 更新记录
作者: xpycc, 点击223次, 评论(0), 收藏者(0)

开关行号, 全选(Ctrl+C复制) | 一键复制:HTML, BBCode(Discuz!) , 源代码 | 查看:裸代码, 全屏
背景
主题: 字体:
C++语言: Type_Template_Level.h
01 #ifndef TYPE_TEMPLATE_LEVEL_H_INCLUDED
02 #define TYPE_TEMPLATE_LEVEL_H_INCLUDED
03
04 #include <climits>
05
06 template <class T>
07 struct Level{
08     static const int Result=INT_MAX;   //假定用户自定类型最高
09 };
10   /*
11    *  如果用户有多个自定义数字类型
12    *  并且他写了这些数字类型的转换接口
13    *  那么需要这么写
14    *  template <class T>
15    *  struct Level{
16    *      static const int Result=T::TypeLevel;
17    *  };
18    *  但这样一来,用户自定义类型必须要定义TypeLevel
19    *  不过相信这并不困难,因为STL的很多算法都需要用户提供接口才能使用
20    */
21
22 //内置类型优先级
23 template <>
24 struct Level<signed char>{
25     static const int Result=1;
26 };
27
28 template <>
29 struct Level<short>{
30     static const int Result=2;
31 };
32
33 template <>
34 struct Level<int>{
35     static const int Result=3;
36 };
37
38 template <>
39 struct Level<long>{
40     static const int Result=4;
41 };
42
43 template <>
44 struct Level<float>{
45     static const int Result=5;
46 };
47
48 template <>
49 struct Level<long long>{
50     static const int Result=6;
51 };
52
53 template <>
54 struct Level<double>{
55     static const int Result=7;
56 };
57
58 template <>
59 struct Level<long double>{
60     static const int Result=8;
61 };
62
63 template <class T,class V,
64           bool flag=(Level<T>::Result > Level<V>::Result) >
65           //精度大小比较,这个小括号必须加
66           //不然编译器会以为是尖括号的结束
67 struct HigherType{  //true的情况
68     typedef T Result;
69 };
70
71 template <class T,class V>
72 struct HigherType<T,V,false>{ //false的情况
73     typedef V Result;
74 };
75
76 #endif // TYPE_TEMPLATE_LEVEL_H_INCLUDED
打分:

所有评论,共0条:( 我也来说两句)


发表评论

注册登录后再发表评论