【问题标题】:Class template with factories带工厂的类模板
【发布时间】:2021-05-03 13:57:40
【问题描述】:

我正在尝试在 C++ 中实现一个非常基本的工厂模式,即

class Base {};
class Derived1 : public Base {};
class Derived2 : public Base {};

而且用法可能看起来像

Base* o1 = new Derived();

但是对于类模板我不知道如何继续

template <class T>
class Base {};
template <class T>
class Derived : public Base<int> {};

在这种情况下,Base* 会是什么样子?

不幸的是,在我的情况下,使用 auto 不是一种选择,我希望能够让客户不必知道实际的 T 是什么

【问题讨论】:

  • 你的意思是所有 Base 类型都应该继承自一些常见的、非模板化的 ActualBase?
  • "在这种情况下,Base* 会是什么样子?" 在这种情况下,您必须改为写 Base&lt;int&gt; * o1 = new Derived;... 除非按照建议 @ 987654321@,你让你的Base 类继承了一个非模板化的实际基类。
  • @Wyck 如果我理解正确,您是说我应该能够执行以下操作? class Base {} 模板 class TBAse : public Base {} template class Derived : public TBase Base* d = new Derived()?

标签: c++ templates factory


【解决方案1】:

template <class T> class Base {};

template <class T>
class Derived : public Base<int> {};

你可能会这样做

Base<int>* b_int = new Derived<char>; // All Derived<T> has base Base<int>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 2012-07-14
    相关资源
    最近更新 更多