类标志的模板专门化

Template specialization for class flags

本文关键字:专门化 标志      更新时间:2023-10-16

我想知道下面的部分专门化,在这里我基于一个泛型List模板定义有序和无序列表,是否是正确的,有效的方法。

template <typename T, bool O> class List;                                       
template <typename T> class UList: public List<T,false>{};                      
template <typename T> class OList: public List<T,true>{};

谢谢,

对于这样的内容,我会使用策略类来定义如何将内容插入到单个列表中,例如

struct DefaultInsertionPolicy
{
  template <typename ContainerType, typename ValueType>
  static void insert(ContainerType& container, ValueType const& cValue)
  {
    container.insert(container.end(), cValue);
  }
};
struct SortedInsertionPolicy
{
  template <typename ContainerType, typename ValueType>
  static void insert(ContainerType& container, ValueType const& cValue)
  {
    // I'm using lower_bound here, but do what is necessary for you
    typename ContainerType::iterator ft = std::lower_bound(container.begin(), container.end(), cValue);
    container.insert(ft, cValue);
  }
};
template <typename T, typename InsertPolicy = DefaultInsertionPolicy>
class List
{
  :
  // insert function
  void insert(T const& cValue)
  {
    InsertPolicy::insert(*this, cValue); // delegate to the policy to do the insert
  }
  void insert(iterator iPos, T const& cValue)
  {
    // do the real insertion at the provided position.
  }
};

所以实类型可以是

typedef List<some_type> UList; // insertion order
typedef List<some_type, SortedInsertionPolicy> OList; // sorted list

我认为您希望通过减少用户最终将在其代码中使用的类的模板参数的数量来降低类模板的泛型。如果是这样,那么在c++ 03和c++ 98中,您可以这样做,即定义从更泛型的类派生的不那么泛型的类。

然而,在c++ 11中,不需要定义新的类模板。相反,您可以创建模板别名,减少模板参数的数量,同时:

template <typename T> 
using UList = List<T,false>;                      
template <typename T> 
using OList = List<T,true>;

使用UListOList,就好像它是一个类模板,接受一个类型参数:

UList<int> uints;
OList<float> ofloats;

在wiki中,我刚刚学会了这种定义类型/别名的新方法,这是我们以前使用typedef来做的:

using语法也可以用作c++ 11中的类型混叠:

typedef void (*Type)(double);         // Old style
using OtherType = void (*)(double);   // New introduced syntax