来自纯抽象基础的typedef继承 [英] typedef inheritance from a pure abstract base

查看:163
本文介绍了来自纯抽象基础的typedef继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编辑:找到重复

我已经将一些问题代码缩小到最简单的工作情况,以说明如下:我的纯粹的抽象基类中的typedef不被派生类继承。在下面的代码中,我想继承 system_t typedef到 ConcreteTemplateMethod 中:

I've whittled down some problem code to the simplest working case to illustrate the following: my typedef in a pure abstract base class is not being inherited by the derived class. In the code below I'd like to inherit the system_t typedef into the ConcreteTemplateMethod:

#include <iostream>

// pure abstract template-method
template <typename T>   // T == Analyzer<U>
class TemplateMethod {
  public:
    typedef T system_t;

    virtual void fn (const system_t& t) const = 0;
};


template <typename T>
class Analyzer {
  public:
    void TemplatedAlgorithm (const TemplateMethod< Analyzer <T> >& a) const {
      printf ("Analyzer::TemplatedAlgorithm\n");
      a.fn(*this);  // run the template-method
    }

    void fn () const {
      printf ("Analyzer::fn\n");
    }
};


// concrete template-method
template <typename T>
class ConcreteTemplateMethod : public TemplateMethod < Analyzer<T> > {
  public:
    typedef Analyzer<T> system_t;

    virtual void fn (const system_t& t) const {
      printf ("ConcreteTemplateMethod::fn\n");
      t.fn(); // perform Analyzer's fn
    }
};

int main () {

  Analyzer <double> a;
  ConcreteTemplateMethod<double> dtm;
  a.TemplatedAlgorithm(dtm);

  return 0;
}

此代码根据预期进行编译和运行。在 ConcreteTemplateMethod 中,需要以下内容,删除时会导致编译器错误:

This code compiles and runs as expected. In the ConcreteTemplateMethod the following is required, and when removed causes compiler errors:

typedef Analyzer<T> system_t;

请注意, system_t 但是,在基类中,code> typedef '。为什么在继承时我必须包含另一个typedef?

Note that the system_t type is already typedef'ed in the base class, however. Why must I include another typedef when inheriting?

我意识到我可以在派生中定义 system_t 的类型名称 ConcreteTemplateMethod 通过使用 typename TemplateMethod<分析器< T> > :: system_t& ,但这有点冗长,我想避免每次我不得不将 typedef 继承并需要使用相同的 system_t 。有没有办法,我可以在基础中定义 TemplateMethod

I realize that I can qualify the typename of system_t in the derived ConcreteTemplateMethod by using typename TemplateMethod< Analyzer<T> >::system_t&, but that's a bit verbose, and I'd like to avoid having to re-typedef to the base everytime I inherit and need to use that same system_t. Is there a way around this that I can define in the base TemplateMethod?

推荐答案

你应该做

typedef typename TemplateMethod<X>::system_t system_t;

以继承typedef。 typedef不会自动继承(如果编译器是兼容的)。

to "inherit" typedef. typedef is not automatically inherited (if compiler is compliant).

如果您浏览堆栈溢出,则会在某处复制此问题。

if you look through stack overflow, there will be duplicate of this question somewhere.

这篇关于来自纯抽象基础的typedef继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆