138.模板与异常

  1 #include<iostream>
  2 using namespace std;
  3 
  4 //错误模板类
  5 template<class T>
  6 class error
  7 {
  8     T t;
  9 public:
 10     void showerror()
 11     {
 12         cout << typeid(T).name() << "   show  error";
 13     }
 14 
 15 };
 16 
 17 //在模板类中可以抛出的错误
 18 class myerror
 19 {
 20 
 21 };
 22 
 23 template < class T >
 24 class  print3d
 25 {
 26 public:
 27     print3d(T t);
 28 
 29     class myerror1
 30     {
 31 
 32     };
 33 
 34     template < class T >
 35     class myerror2
 36     {
 37         if (t<1)
 38         {
 39             //抛出嵌套类的错误
 40             //throw  print3d<T>::myerror1();
 41             //抛出内部类的模板对象(指定类型)
 42             throw  print3d<T>::myerror2<int>();
 43             //抛出内部类的模板对象(不指定类型)
 44             throw  print3d<T>::myerror2<T>();
 45             //抛出外部模板错误
 46             //throw error<T>();
 47         }
 48         else if (t>100)
 49         {
 50             //throw error<T>();
 51             //抛出一个外部错误
 52             throw myerror();
 53         }
 54     };
 55 
 56 };
 57 
 58 //模板函数使用模板异常
 59 template <class T>
 60 void go()
 61 {
 62     try
 63     {
 64         
 65         print3d<T> my3d1(0);
 66     }
 67     catch (error<T>  e)
 68     {
 69         e.showerror();
 70     }
 71     catch (print3d<T>::myerror2<T> e)
 72     {
 73 
 74     }
 75     catch (print3d<T>::myerror2<int> e)
 76     {
 77 
 78     }
 79 }
 80 
 81 
 82 void main()
 83 {
 84     go<double>();
 85     //try
 86     //{
 87     //    //print3d<int> my3d1(0);
 88     //    print3d<char > my3d1(0);
 89     //}
 90     //catch (error<int>  e)
 91     //{
 92     //    e.showerror();
 93     //}
 94     //catch (error<char>  e)
 95     //{
 96     //    e.showerror();
 97     //}
 98     //模板与模板需要传递T参数
 99     //常规引用模板必须实例化error<int>
100     //模板直接引用常规
101     // throw  print3d<T>::myerror1()  类模板中嵌套类
102     //throw  print3d<T>::myerror2<int>(); 
103     //throw  print3d<T>::myerror2<T>();   类模板中嵌套类模板
104     cin.get();
105 }

 

posted @ 2018-04-01 22:41  喵小喵~  阅读(139)  评论(0编辑  收藏  举报