Effective C++ Item 41 了解隐式接口和编译期多态

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


经验:class 和 templates 都支持接口和多态。


对 classes 而言接口是显式的,以函数签名为中心。多态则是通过 virtual 函数发生于执行期
对 templates 參数而言,接口是隐式的,奠基于有效表达式。多态则是通过 templates 详细化和函数重载解析(function overloading resolution)发生于编译期。


演示样例1:显式接口和执行期多态

class Widget{
public:
	Widget();
	virtual ~Widget();
	virtual std::size_t size() const;
	virtual swap(Widget &other);
	//...
};


void doProcessing(Widget &w){ // w的类型被声明为 Widget,所以 w 必须支持 Widget 接口。

Widget 的接口能够在 class Widget 中看到,是显式接口 if(w.size() > 10 && w != someNastyWidget){ //因为 Widget 的 size() 方法被声明为 virtual 。所以 w 对它的调用将出执行期多态 Widget temp(w); temp.normalize(); temp.swap(w); } }



演示样例2:隐式接口和编译期多态

template<typename T>
void doProcessing(T &w){
	if(w.size() > 10 && w != someNastyWidget){
		T temp(w);
		temp.normalize();
		temp.swap(w);
	}
}


解析:w 必须支持哪一种接口,并不能从哪个地方显式地看出。仅仅能从 template 中运行于 w 身上的操作来决定,是隐式接口。
本例中 w 的类型T好像必须技 size, normalize, swap, copy构造函数, 不等比較。


以不同的 template 參数详细化 function template 会导致调用不同的函数,这便 所谓的编译期多态。


原文地址:https://www.cnblogs.com/cxchanpin/p/6887863.html