سؤال

I have the following (examplery) classes

class ComponentA : public ComponentBase {
  Renderer renderer;
}

class Renderer {
  Renderer(std::vector<float> verts) : vertices(verts){};
  std::vector<float> vertices;
}

I'd like to keep my derived component classes flexible, so there could be many different renderers and of course other objects that are part of the component.

The renderer class does not have a default constructor, so I'd have to initialise it in the component's initialiser list or directly in the component's header file. Alternatively I could add a default constructor to renderer, but what if I have a class where a default constructor doesn't make sense or I don't want to implement one since it would require extra handling (ie setting a flag that the object isn't properly initialised)?

Additionally, the renderer could potentially not be necessary for the whole lifetime of the component, which would again require renderer to have some sort of "off" switch.

Now of course a (unique) pointer would solve the problem, but I'd like to avoid that if not necessary.

Are there any idioms/solutions to this problem I could use to handle these cases?

هل كانت مفيدة؟

المحلول

Is what you are looking for not just classical inherritance? I.e. something Like

class ComponentA : public ComponentBase {
  RendererBase& renderer;
  ComponentA(RederBase& r):renderer(r) {} 
}

class RenderBase {
  // Maybe some mandetory virtual functions in here
};

class RendererTypeFloat : public RenderBase {
  RendererTypeFloat(std::vector<float> verts) : vertices(verts){};
  std::vector<float> vertices;
}

class RendererTypeInt : public RenderBase {
  RendererTypeInt(std::vector<int> verts) : vertices(verts){};
  std::vector<int> vertices;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top