I am working in C++ and I have this problem. class Container { Container(int whi
ID: 654357 • Letter: I
Question
I am working in C++ and I have this problem.
class Container {
Container(int which_type_to_use_a_b_or_c);
A & getData(A & prototype);
B & getData(B & prototype);
C & getData(C & prototype);
private:
A a;
B b;
C c;
int type_used;
}
Only one of the A,B or C datatypes is actually used in a class Container instantiation. The constructor flag decides which one to use. When it's time to get a reference to the internal object, I need a getData routine which returns the reference of the different type. In order to disambiguate, I pass a "prototype" A() B() or C().
I don't really like this pattern, but I am unable to find anything better due to my limited palette in c++. Do you have any other approach available? please note that templating Container over A, B or C is not an option due to other constraints.
Explanation / Answer
You could use a discriminated union, like Boost.Variant
class Container {
typedef boost::variant<A,B,C> ABC;
enum Type { UseA, UseB, UseC };
explicit Container(Type t);
ABC & getData();
private:
ABC value;
}
but frankly this feels like an X-Y problem. What are you actually trying to accomplish?
NB. you said in a comment
... we also can't use pointers, only references
you may be interested to know that runtime polymorphism works just fine with references (even if it doesn't help here).