理解策略模板的定义

understanding the definition of policy-based template

本文关键字:定义 策略      更新时间:2023-10-16
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>而另一行没有?

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
值得注意的是,这种习惯用法被称为"基于策略的设计"。