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

开发者在线 Builder.com.cn 更新时间:2008-02-05作者:guanwl 来源:CSDN

本文关键词: 转换 任意 类型 自定义

定义如下的一个类
      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;
    }
通过特化可以在不改变类定义的情况下。为定义的类添加恰当的转型操作,使这种转换成为一个有意义的转换。
 
查看本文来源

用户评论

  • 用户名
  • 评论内容