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?