1 背景
参考资料[1]P218的条款45:运用成员函数模板接受所有兼容类型,提出了如何使得自定义的智能指针支持隐式类型转换的方法,其中用到的技巧就是使用成员函数模板。关于其详细的原理,书中已经说的很清楚,只是在编程的过程中会遇到挫折,故在此记录一下成功通过的编译的代码(见下一章)。
2 代码
template< class T >
class SmartPtr {
public:
// constructor
template< class Y >
explicit SmartPtr( Y* t ){}
// copy constructor
template< class Y >
SmartPtr( SmartPtr< Y > const &other ){ }
};
class Top{};
class Middle:public Top
{};
int main( void )
{
SmartPtr< Top > pt1 = SmartPtr< Middle >( new Middle );
return 0;
}
说明:
a)new Middle要使用到构造函数,因此SmartPtr的第一个构造函数必须定义,否则无法通过编译;
b)将Middle型指针转换为Top型指针,需要用到copy构造函数,因此SmartPtr的第二个构造函数必须定义,否则无法通过编译。
参考资料
[1]Effective C++,中文版(第三版)