【问题标题】:Inheritance of a template class [closed]模板类的继承[关闭]
【发布时间】:2016-11-22 18:13:19
【问题描述】:
template <typename T>
class store  // Very basic class, capable of accepting any data-type and does nothing too much
{
  public:
    store(T value) : value(value) {}
  private:
    T value;
}

template <>
class store<int>  // Inherits all the basic functionality that the above class has and it also has additional methods
: public store<int> // PROBLEM OVER HERE. How do I refer to the above class?
{
  public:
    store(int value) : store<int>(value) /* PROBLEM OVER HERE. Should refer to the constructor of the above class */ {}
    void my_additional_int_method();
}

这里我有继承问题。我不想更改基类的名称,因为基类与所有派生类的用途相同(唯一的区别 - 派生类几乎没有额外的方法)

【问题讨论】:

  • “请添加一些上下文来解释代码部分(或者...看起来您的帖子主要是代码;请添加更多详细信息” 所以你注意到了吗?
  • 您正在尝试创建一个继承的类,嗯,它本身?什么?这是一种专业化的尝试吗?
  • 我知道继承派生类本身是没有意义的。我的问题是如何引用基类?
  • @user3600124 至于你的几个额外的方法,这些是要从公共接口调用,还是只能在内部使用?

标签: c++


【解决方案1】:

你也许可以这样做:

template <typename T>
class store_impl
{
  public:
    store_impl(T value) : value(value) {}
  private:
    T value;
}

// default class accepting any type
// provides the default methods
template <typename T>
class store: public store_impl<T>
{
public:
    store(T value) : store_impl(value) {}
}

// specialization for int with extra methods
template <>
class store<int>: public store_impl<int>
{
  public:
    store(int value) : store_impl<int>(value)
    {}
    void my_additional_int_method();
}

【讨论】:

  • 使用 mixin 来扩展专业化接口是一个非常好的主意。
  • 标记为最佳答案。找不到更好的方法
【解决方案2】:

你不能给一个类指定一个专门模板的名字:

template <>
class store<int>

你能做的就是给它一个具体的类型名:

class store_int : public store<int>

或使用typedefusing 语句

typdef store<int> store_int;

using store_int = store<int>;

【讨论】:

    猜你喜欢
    • 2014-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    • 1970-01-01
    相关资源
    最近更新 更多