This question is based on Create objects in conditional c++ statements.
However, in my case I need to declare one object from a choice of multiple classes which will then be passed as argument to a function. Hence, the object has to be declared with a pre-defined name (obj in this case).
Class1 obj;
Class2 obj;
if (...) {
obj = Class1(); }
if (...) {
obj = Class1(a, b); }
else
obj = Class2();
// Do something on declared object
DoSomething(obj.variable_);
Currently the above will not work because of conflicting declaration of obj
. How should I go about doing this?
You might not need std::variant
, if your object doesn't have to be "polymorphic" at run-time. Refactor your code to:
if (...) {
DoSomething(Class1());
if (...) {
DoSomething(Class1(a, b));
else
DoSomething(Class2());
And make DoSomething
a template or overload set:
void DoSomething(const Class1&) { }
void DoSomething(const Class2&) { }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With