【问题标题】:Are there any benefits to inheriting from an abstract template class?从抽象模板类继承有什么好处吗?
【发布时间】:2012-11-22 10:12:51
【问题描述】:

我的意思是执行以下操作:

template<class Type> class Foo {
public:
... // Code Here.
};

class Bar : public Foo<Type> {
public:
...
};

声明类 Bar 时的 Type 实际上是一个类型(int、bool 等)或预先创建的类型。

如果这个问题太模糊,或者如果它已经被回答,请告诉我。

【问题讨论】:

  • 您的问题解决了吗?如果是这样,您能否对答案进行投票并接受?如果没有,请编辑您的问题并提供更多详细信息。

标签: class templates inheritance abstract base


【解决方案1】:

语言功能是否有用,实际上取决于您使用它的方式和位置。对于从模板化抽象模板继承,这是我能想到的一个假设场景,它可能有用。

template <typename Type> class Gadget {
public:
    string name() = 0;
};

class SmartPhone : public Gadget<Phone> {
public:
    string name() { return "I am a smart phone"; }
};

class SportsCar : public Gadget<Car> {
public:
    string name() { return "I am a sports car"; }
};

vector<Gadget*> inventory;
inventory.push_back(new SmartPhone());
inventory.push_back(new SportsCar());
// etc ...

请注意,这可能不是实现它的最佳方式,但我的观点是,您总能找到对所有事物都有用处的方法。 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 2011-01-10
    • 1970-01-01
    • 2011-05-06
    相关资源
    最近更新 更多