2011-12-19 114 views
2
template < 
    typename T, 
    template <class> class OwnershipPolicy = RefCounted, #1 
    class ConversionPolicy = DisallowConversion,   #2 
    template <class> class CheckingPolicy = AssertCheck, 
    template <class> class StoragePolicy = DefaultSPStorage 
> 
class SmartPtr; 

Q1的定义>什么是行#1理解基于策略的模板

template <class> class OwnershipPolicy = RefCounted, 

语法,为什么它不提供参数,如下?

template <class T2> class OwnershipPolicy = RefCounted, 

Q2>之间有什么#1#2不同?

template <class> class OwnershipPolicy = RefCounted, 

class ConversionPolicy = DisallowConversion, 

为什么其中一行有template<class>而另一行却没有?

回答

4

template <class> class OwnershipPolicy是模板模板参数。即预计OwnershipPolicy是一个采用一个(且只有一个)类型参数的模板。这个参数没有名称,因为它不是必需的,而且无论如何你都无法使用它。

class ConversionPolicy相当于typename ConversionPolicy,即任何普通类型的论点。

区别在于你如何使用它。对于模板模板参数,您只提供模板的名称,您可以稍后使用它来实例化具体类型。对于typename,你需要一个具体的类型:

template <typename A, template <typename> class B> 
struct foo {}; 

template <typename T> 
struct x {}; 

struct y {}; 

template <typename T, typename U> 
struct z {}; 

// both of these are valid: 
foo<x<int>, x> a; 
foo<y, x> b; 
// these are not: 
foo<y, x<int>> c; 
foo<y, y> d; 
foo<y, z> e; // z has two template arguments, B must have only one 

值得注意的是,成语叫做“基于策略的设计”。