CSDN专家博客精华版

为人民服务!
  首页  :: 新随笔  :: 管理

让自定义的类型可以和任意的类型之间转换

Posted on 2007-12-17 10:51  csdnexpert  阅读(118)  评论(0)    收藏  举报
定义如下的一个类
      struct cls
    {
         template<typename T>
         operator T()
         {
             return T();
         }
 
         template< typename T>
         cls(const T&)
         {
         }
         cls(){}
 
 
    };
现在这个类可以和其它的任意的类型之间进行转换了。测试如下
 
 
    void test()
    {
         cls o;
         cls o2(3);
         cls o3(7.9);
         cout << (int)o << (char) o2 << (double)o3 << endl;
    }
 
但是现在这种转换是没有意义的。要想使这种转换有意义,我们只需特化它的一些转换方法就行了。例如做如下的特化。
 
     template<>
    cls::cls(const int& a)
    {
         cout << "int -> cls" << endl;
    }
 
    template<>
    cls::operator int()
    {
         cout << "cls->int" << endl;
         return 8;
    }
通过特化可以在不改变类定义的情况下。为定义的类添加恰当的转型操作,使这种转换成为一个有意义的转换。
 


Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=1542905