模板类使用成员函数模板(member function template)处理隐式(implicit)转换

来源:互联网 发布:好书推荐知乎 编辑:程序博客网 时间:2024/05/30 05:00

指针支持隐式转换(implicit conversion), 在动态绑定中,派生类指针可以转换为基类指针.

但是模板的实例化(instantiations)之间, 是单独存在的,

派生类的实例化的模板(SmartPtr<Derived>), 不能转换为基类实例化的模板(SmartPtr<Base>);


需要明确的编写, 因为派生类也可以继续做为基类, 产生派生类, 所以无法直接写出构造函数.

使用成员函数模板(member function template), 再声明一个模板参数, 提供这种隐式转换.


为了使用转换只能发生在可以转换的指针, 如"Derived->Base", 不能逆序, 所以引入相关约束判断是否可以转换.

在成员初始化列表(member initialization list)中调用get()函数, 判断是否可以隐式转换.


使用成员函数模板的构造函数, 是成员函数的一种, 并不是重载复制构造函数, 所以类会自动生成一个默认构造函数.


代码注意: 第一个可以转换, 第二个不能转换, 第三个使用默认的构造函数.

/*
 * test.cpp
 *
 *  Created on: 2014.04.20
 *      Author: Spike
 */
       
/*eclipse cdt, gcc 4.8.1*/
       
#include <iostream>  
       
using namespace std;  
       
class Base{};  
       
class Derived : public Base {};  
       
template<typename T>  
class SmartPtr {  
public:  
    SmartPtr() = default;  
    template<typename U>  
    SmartPtr(const SmartPtr<U>& other)  
        : heldPtr(other.get()) {  
        std::cout << "SmartPtr:CopyConstructor" << std::endl;  
    }  
    T* get() const {return heldPtr;}  
private:  
    T* heldPtr;  
};  
       
int main() {  
       
    SmartPtr<Derived> spd;  
    SmartPtr<Base> spb(spd);  
       
    //SmartPtr<Base> spb1;  
    //SmartPtr<Derived> spd1(spb1); //无法进行隐身转换  
       
    SmartPtr<Base> spd2;  
    SmartPtr<Base> spd21(spd2); //使用默认的复制构造函数  
    return 0;  
}

0 0
原创粉丝点击