类模板专门化于泛型类模板
Class template specialized on generic class template
我有一个类族,我想为它们写一个抽象工厂。下面这个最小的例子会给你一个大致的概念。
我的问题是我不知道如何定义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());}
};
看到显示。
相关文章:
- C++泛型类错误,问题出在哪里?
- C++泛型类,单独实现?
- 如何在 C++ 中声明泛型类
- 在C++中分配泛型类
- 基于变量输入的泛型类方法计算
- C++处理取消引用语法的泛型类
- 用于重载的泛型类成员函数
- 将类型作为指向另一个类的对象的指针的泛型类-NOT WORKING
- 在泛型类中使用带有 CUDA 关键字的模板类
- 在类中使用泛型类成员
- 如何在main中重载运算符>泛型类.cpp
- C++泛型类中的字段/属性
- 用返回子类的方法设计C++泛型类
- C++ 堆栈泛型类,int 变量将 32765 作为值而不是 1
- 将资源移出泛型类
- C++中的泛型类
- 可以在泛型类中为一种类型提供一个可用的函数
- 如何在C++中从泛型类创建对象
- 用泛型类专门化模板函数
- 类模板专门化于泛型类模板