类模板专门化于泛型类模板

Class template specialized on generic class template

本文关键字:泛型类 专门化      更新时间:2023-10-16

我有一个类族,我想为它们写一个抽象工厂。下面这个最小的例子会给你一个大致的概念。

我的问题是我不知道如何定义ConcreteFactory>的成员函数。clang++报告这个错误:

template-class-of-template-class.cc:36:39: error: nested name specifier 'ConcreteFactory<Derived<NUM> >::' for
      declaration does not refer into a class, class template or class template partial specialization
Base* ConcreteFactory<Derived<NUM> >::construct() const

我只能为完全指定的类定义它们,例如:ConcreteFactory>。如果我必须这样做的话,会有很多重复的代码。是否有任何方法可以避免通过智能使用模板来编写这个样板文件?

#include <cstdlib>
class Base
{
};
template <typename NUM>
class Derived : public Base
{
public:
  Derived(NUM const &thing) : m_thing(thing) {}
  ~Derived() {}
private:
  NUM m_thing;
};
class AbstractFactory
{
public:
  virtual Base *construct() const = 0;
};

template <class Y>
class ConcreteFactory
{
public:
  Base* construct() const
  {
    return new Y();
  }
};
template <typename NUM>
template <>
Base* ConcreteFactory<Derived<NUM> >::construct() const
{
  return new Derived<NUM>(rand());
}
int main(int argc, char *argv[])
{
  ConcreteFactory<Base> baseFact;
  ConcreteFactory<Derived<int> > intFact;
  ConcreteFactory<Derived<double> > doubleFact;
  Base* a = baseFact.construct();
  Base* b = intFact.construct();
  Base* c = doubleFact.construct();
  delete c;
  delete b;
  delete a;
}
  • 不能部分特化模板类的成员函数

  • 你必须对整个模板类进行部分专门化。

  • 见更正后的代码:


// partial specialization of class `ConcreteFactory`
template<typename NUM>
class ConcreteFactory<Derived<NUM>> {
  public:
    Base* construct() const { return new Derived<NUM>(rand());}
};

看到显示。