专用于泛型类模板的类模板

时间:2014-06-09 23:13:52

标签: c++ templates template-specialization

我有一系列课程,我想写一个抽象工厂。下面的最小例子将为您提供一般的想法。

我的问题是我无法弄清楚如何定义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&gt;。如果我必须这样做,将会有大量重复的代码。有没有办法避免通过智能使用模板来编写这个样板?

#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;
}

1 个答案:

答案 0 :(得分:1)

  • 您无法部分专注于模板类的成员函数。

  • 您必须部分专门化整个模板类。

  • 请参阅以下更正的代码:


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

请参阅Display