C++惯用法:通过成员模板实现隐式转换(Coercion by Member Template)

往往将子类指针转换成父类指针进行操作是常见的且是非常有用的,如下

class base {}; class derive : public base {}; base* pb = NULL; derive* pd = NULL; pb = pd;

 

同样,对于内建类型(built-in type)的隐式转换也是常见的,如下

char c = 'A'; short s = 0; int n = 0; float f = 0.f; double d = 0.0; f = d; n = f; s = n; c = s;

 

然而在很多时候,会出现对某一类型的封装进行管理,如下定义一类型包装类

template<typename T> class type_wrapper { public: type_wrapper() : value_() {} type_wrapper(T const& value) : value_(value) {} type_wrapper(type_wrapper<T> const& rhs) : value_(rhs.value_) {} type_wrapper<T>& operator=(type_wrapper<T> const& rhs) { value_ = rhs.value_; return (*this); } operator T const&() const { return value_; } T value_; };

 

此时,对于同类型的拷贝与赋值不会出现问题

 

然而对于向上类型转换却不能通过编译,但这往往是直观并应该正确的,如下

type_wrapper<base *> tpb = pb; type_wrapper<derive *> tpd = pd; // compile error tpb = tpd; type_wrapper<char> tc = c; type_wrapper<int> tn = n; // compile error tc = tn;

 

解决方法便是使用Coercion by Member Template惯用法,新增两个成员模板函数

template<typename Other> type_wrapper(type_wrapper<Other> const& rhs) : value_(rhs.value_) {} template<typename Other> type_wrapper<T>& operator=(type_wrapper<Other> const& rhs) { value_ = rhs.value_; return (*this); }

 

此时上面的编译便能成功

// OK tpb = tpd; // Warning but OK tc = tn;

 

附注:

Coercion by Member Template 惯用法在很多地方能见到它的身影,如std::auto_ptr, boost::shared_ptr, std::allocator等

 

英文链接:http://en.wikibooks.org/wiki/More_C++_Idioms/Coercion_by_Member_Template

 

你可能感兴趣的:(C++,c,Class,wrapper)