我正在为项目创建内存池,但是在编译时遇到了问题:

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

我以为我可以列出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 ++模板不是covariant

作为解决方案,我首先想到的是在R类中保留Descriptor*,以Descriptor作为模板参数实例化所有R,并在构造新R时传递Descriptor的不同子类。

关于c++ - 不同子类的C++链接列表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22846197/

10-15 06:54