为了描述问题,根据《 C++设计新思维泛型编程与设计模式之应用》的2.6节的例子中,NitifyContainer中有一个数据结构用来存储类型T的实现,但是这个类型T有可能是多态的,在多态的情况下,存储指针,反之存储对象(你也可以不用这么做,这里只是为了描述这个问题),好了。《 C++设计新思维泛型编程与设计模式之应用》书中给出了第一种解决方案,代码如下所示:
template<class T, bool isPolyMorphic>
struct NitifyContainerValueTrait {
typedef T *ValueType;
};
template<class T>
struct NitifyContainerValueTrait<T, false> {
typedef T ValueType;
};
template<class T, bool isPolyMorphic>
class NitifyContainer {
typedef NitifyContainerValueTrait<T, isPolyMorphic>::ValueType ValueType;
};
这里通过bool型参数isPolyMorphic来决定ValueType的类型。
书中还提供了另外一种写法,如下
template <bool isPolyMorphic,typename T,typename U> struct Select{
typedef T Result;
};
template <typename T,typename U> struct Select<false,T,U>{
typedef U Result;
};
template<bool isPolyMorphic,typename T, typename U>
class NitifyContainer {
typedef typename Select<isPolyMorphic,T,U>::Result ValueType;
};
仔细看一下这两种解决方式,初看之下,啥区别都没有,对吧?对头,没错,我也没看出啥。
但是仔细分析一下,第二种写法直接导致了Result的类型取决于模板参数的类型,因此类型的种类多少,无关紧要。而第一种不是,第一种的写法导致类型的定义是有限制的,因为你永远不知道,模板参数T传递的到底是啥??所以 typedef T ValueType就存在着很大的限制,当然了,这个只是我个人的理解。
根据原书的解答,实在是不知所云,哈哈