Consider a class with a deleted default constructor (my actual class is much more complicated and the default constructor is deleted implicitly due to one of its members having a deleted default constructor). I would like to instantiate my class with one of its constructors based on the value of some input and then do "a bunch of things". The following code shows two ways that this can't be done for the reasons stated in the code comments, but gives an idea of what I'm trying to achieve.
#include <vector>
class A {
bool m_with_v;
int m_i;
std::vector<double> m_v;
public:
A() = delete;
A(int i) : m_i(i), m_with_v(false) {}
A(int i, std::vector<double> v) : m_i(i), m_v(v), m_with_v(true) {}
auto do_stuff() { /* do stuff depending on m_with_v */ };
};
int main(int argc, char* argv[])
{
bool yes_no;
/* Obtain a value for yes_no from argv */
A a; // the default constructor of "A" cannot be referenced -- it is a deleted function
if (yes_no)
a = A(1);
else {
std::vector<double> v{ 1,2,3 };
a = A(1, v);
}
a.do_stuff();
// do a bunch more things
if (yes_no)
A b(1);
else {
std::vector<double> v{ 1,2,3 };
A b(1, v);
}
b.do_stuff(); // identifier "b" is undefined, i.e. it's gone out of scope
// do a bunch more things
}
One obvious way to do this would be to move the "bunch of things" inside each part of the if
block, but that would result in a lot of duplicate code, which I want to avoid.
Another obvious way would be to create a function to do the "bunch of things" and call that in each part of the if
block, but this requires a certain amount of refactoring and the function call could become fairly ugly if there are a large number of variables that need to be passed to it.
So, my question is: Is there some way to conditionally instantiate my class and have it available in the surrounding scope?