Reputation: 807
Depending on a boolean variable myBool
I would like to declare a variable mVect
as a 1D or a 2D vector, i.e.:
if (myBool){
vector < vector< float > > myVect;
}
else{
vector <float> myVect;
}
///// later.....//////
//call many instances of overloaded myFn( vector<float>),
//or myFn ( vector<vector<float>)
//// more stuff.....//
// call more instances of myFn
I'd like the variables to have scope beyond the if statement. Using a ternary operator as in (Expand scope of a variable initialized in a if/else sequence) does not seem applicable since the variable types are different.
My motivation for this is that I have an overloaded function myFn
, one version inputs a vector
, another puts in a vector<vector>
. I'd prefer to not put an if statement in myFn
to distinguish the cases for performance reasons -- I'd like to call a single if
statement when declaring and not call a trillion if
statements when repeatedly calling myFn
edit:
This is for a physical simulation. I would like to keep the ability to do a 1D or a 2D calculation and myFn does a 1D or a 2D interpolation respectively. I don't want to modify any of the code-base beyond different initializing of variables and I thus want to keep the variable names the same so I can call the same overloaded interpolator, nor do I want an if statement in the interpolator
Upvotes: 1
Views: 769
Reputation: 44248
One of the solution - OO. You create a base class with interface that used in your code and interpolator and then inherit 1d or 2d from it based on condition:
class MyVector {
public:
virtual ~MyVector();
...
};
class MyVector1D : public MyVector {
};
class MyVector2D : public MyVector {
};
// usage
std::unique_ptr<MyVector> vector = myBool ? std::make_unique<MyVector1D>()
: std::make_unique<MyVector2D>();
myFn( vector );
Or you can use boost::variant with either visitor pattern or conditional code where that vector is used.
Upvotes: 0
Reputation: 2075
If I understand your question correctly you want a local variable to have different types based on runtime value of a boolean.
This is impossible to acheve in C++. The two options you have are:
1) If the boolean is const (or comes from a constexpr) you can convert you code into a template and use std::conditional
to pick the right type.
2) Do all the work inside the respective scopes of your if
, then the variables are different and no problem with them having different types:
if (myBool){
vector < vector< float > > myVect;
...
myFn(myVect);
}
else{
vector <float> myVect;
...
myFn(myVect);
}
Upvotes: 1