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

时间:2014-04-03 18:40:47

标签: c++ templates

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

我有一个内存池类(在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;
}

1 个答案:

答案 0 :(得分:1)

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

我能想到的第一件事就是在R类中保留Descriptor*,用Descriptor作为模板参数实例化所有Rs,并在构造新R时传递Descriptor的不同子类。 / p>