C++ - 模板类模板成员函数(member function template)隐式处理(implicit)变化

模板类模板成员函数(member function template)隐式处理(implicit)变化


本文地址: http://blog.csdn.net/caroline_wendy/article/details/24233693


指针支持隐式转换(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;
}

输出:

SmartPtr:CopyConstructor





版权声明:本文博客原创文章。博客,未经同意,不得转载。

posted @ 2015-07-21 18:23  mengfanrong  阅读(592)  评论(0编辑  收藏  举报