0

For simplicity's sake, say I have a Object Manager class A that manages resources between objects derived from same class class Bs.

A requirements are these:

1) Should have an instance of only one B at a time, we'll make that current B

2) Should remember the name or enum representation of the previous B so it can recreate when that B needs to be the current B again.

3) A has resources a, b, c, d

4) A is responsible for giving the current B only the resources the current B requires when it becomes the current B

the current implementation is like this. I'm hoping there is a better way since all the static_cast are annoying me.

class B
{
 public:
   void show()
 }

class Recording : public B
{
}

class Camera : public B
{
} 

class A
{
 a a;
 b b;
 c c;
 d d;

 enum Benum
  {
    Recording,
    Camera,
    InputSource,
    COUNT,
  }
 map<Benum, unique_ptr<B> Bmap;
 B* currentB;
public:

  void init()
  { 
    Bmap[Benum::Recording] = make_uniqe ...
    Bmap[Benum::Camera] = make_uniqe ...
    ...
  }

  switchB(Benum b)
  {
  switch(b)
  {
  case Benum::REcording
    auto recording = static_cast<Recording>(Bmap[Benum::Recording].get());
    recording->setup(a, b, c)
    currentB = recording;
  case Benum::Camera
    auto camera = static_cast<CAmera>(Bmap[Benum::Camera].get());
    camera->setup(b, c)
    currentB = camera;

  currentB->show();

This works fine, but just for engineering challenge, is there a better way to do this? To me this seems like a code smell. Reading this, I have to understand that the enum represents the objects. If the enum ever changes the whole class would have to be touched. It just doesn't seem easy to maintain.

Also, all these static_casting and similar codes on switch statement with just different setups seems like a code smell

user3904534
  • 309
  • 5
  • 13
  • Maybe you want a tuple of properly typed `unique_ptr`? Something like `std::tuple, std::unique_ptr, ...>`. – François Andrieux Jan 11 '18 at 17:36
  • How would I call it? – user3904534 Jan 11 '18 at 19:41
  • With [`std::get`](http://en.cppreference.com/w/cpp/utility/tuple/get). [See this question](https://stackoverflow.com/questions/15835762/how-to-get-reference-to-an-element-of-a-stdtuple). You would initialize it with [`std::make_tuple`](http://en.cppreference.com/w/cpp/utility/tuple/make_tuple). Though since you're using a `switch` anyway, you can just keep each kind of `B` as a separate member. – François Andrieux Jan 11 '18 at 19:47

0 Answers0