C++不同子类的链接列表

C++ Linked List of Different SubClasses

本文关键字:链接 列表 子类 C++      更新时间:2023-10-16

我正在努力为一个项目制作内存池,但是我在编译它时遇到了问题:

我有一个内存池类(在下面的 R 示例中),它有一个模板参数来保存实际使用的类。每个类都是描述符的一个子类。

我假设我可以制作 R 对象的链接列表,但是当我尝试附加包含描述符子类的 R 类时,编译器会抱怨类型转换。

关于如何修复此编译错误的任何建议?

 g++-4.7  -g -ggdb -DDEBUG=1   -Wall -std=c++11   -march=native -m64 -DINTEL -fno-strict-aliasing example.cpp -o example.x
example.cpp: In instantiation of ‘void n1::n2::R<D>::add() [with D = n1::n2::SubDescriptor2<int, int>]’:
example.cpp:68:14:   required from here
example.cpp:37:10: error: cannot convert ‘n1::n2::R<n1::n2::SubDescriptor2<int, int> >* const’ to ‘n1::n2::R<n1::n2::Descriptor>*’ in assignment
example.cpp: In instantiation of ‘void n1::n2::R<D>::add() [with D = n1::n3::SubDescriptor<int, int>]’:
example.cpp:72:13:   required from here
example.cpp:37:10: error: cannot convert ‘n1::n2::R<n1::n3::SubDescriptor<int, int> >* const’ to ‘n1::n2::R<n1::n2::Descriptor>*’ in assignment

工作示例:

#include <cstdint>
#include <utility>
#include <stdlib.h>
namespace n1 {
  namespace n2 {
    class Descriptor;
    template<class D>
    class R;

    class Descriptor {
        public:
          int temp;
          Descriptor() {}
          Descriptor(int x) {
            temp = x;
          }
          ~Descriptor() {}
    };
    R<Descriptor> * list = nullptr;
    template<class D>
    class R {
    public:
      R<Descriptor> *pool_next;
      D descriptor; //EDIT for some reason I only had d here...
      template<typename... Args>
      R(Args&&... args): descriptor(std::forward<Args>(args)...) {
      };

      void add() {
         this->pool_next = list;
         list = this;
      }
    };
    template<class T, class W>
      class SubDescriptor2: public Descriptor {
      public:
        SubDescriptor2(int x) {
          temp = x;
        };
        ~SubDescriptor2() {};
      };
  };

  namespace n3{
  template<class T, class W>
    class SubDescriptor: public n2::Descriptor {
    public:
        SubDescriptor(int x) {
          temp = x;
        };
        ~SubDescriptor() {};
    };
  };
};
int main(int argc, const char * argv[]) {
  n1::n2::R<  n1::n2::SubDescriptor2<int, int>  > *temp2;
  temp2 = new n1::n2::R<  n1::n2::SubDescriptor2<int, int>  >(1);
  temp2->add();
  n1::n2::R<  n1::n3::SubDescriptor<int, int> > *temp;
  temp = new n1::n2::R< n1::n3::SubDescriptor<int, int> >(1);
  temp->add();
  return 1;
}

R<SubDescriptor>不是R<Descriptor>的子类。这是因为C++模板不是协变的。

我能想到的第一件事是将Descriptor*保留在 R 类中,使用描述符作为其模板参数实例化所有 R,并在构建新 R 时传递描述符的不同子类。