0

I have two classes Foo and Bar. I have a data loader that loads data from file and return them as Foo or Bar.

Currently I have the solution as:

struct Foo { 
  std::vector<Foo> Filter() {
     //do something with data and return new Foo's
  }
  std::vector<int> data; 
}

struct Bar : protected Foo {
  std::vector<Bar> Filter() {
     //do something with data and return new Bar's
  }
}

template <typename T>
DataLoader<T> { 
    .... 
    T & Get() { ... }
}

where T is either Foo or Bar.

The problem with this solution is that I cannot dynamically choose to return Foo or Bar. I have to reload data. Ue of virtual method is not working, since Filter has different return types. Also, making inheritance public is not an option, because in that case I could do Foo f = Bar(); which I dont want to enable.

I have come up with a solution using multiple inheritance. However, I am not sure if it is correct or it would produce undefined-behaviour.

I have added private class to DataLoader:

struct FooBarStorage : virtual public Foo, public Bar {}

and changed inheritance in Bar to struct Bar : virtual protected Foo.

Now I can have non-templated DataLoader:

class DataLoader {

  template <typename T> T & Get() { ... }
}

and specialise Get to return Bar & or Foo &. The advantage is, I can load data only once and decide what to return in runtime. With a previous solution, data were loaded with a given type (Foo or Bar) and I was not able to change the type.

Is this a possible working solution or would it produce undefined-behaviour / other problems / performance impacts?

Martin Perry
  • 9,232
  • 8
  • 46
  • 114
  • 1
    _"Is this a possible working solution"_ 1st what came to my mind reading through your question. I believe the `virtual` inheritance is exactly to solve that specific purpose. – πάντα ῥεῖ Jun 16 '19 at 07:50
  • Another interesting land to explore is what could be done with `virtual` inheritance in combination with the CRTP. All in all, it's about function call dispatching to the right target instance, no? – πάντα ῥεῖ Jun 16 '19 at 08:18

0 Answers0