Suppose I have variables passed to a function, say func2, by const reference. Subject to some test, I would like to modify its arguments before calling it. Here is a pseudo-code explaining my goal.
struct strA
{
int a;
VectorXd v;
};
strA func2(const int& a, const VectorXd& v){...};
strA func1(...){...};
int main(){
int a;
VectorXd v;
bool test;
if(test){
strA B;
// some amount of work is required to get the members of B
B = func1(...);
func2(B.a, B.v);
} else {
func2(a, v);
};
return 0;
}
This code works fine but for readability and genericity, I am wondering whether a better solution exists. Here is an alternative
strA func3(const int& a, const VectorXd& v, test)
{
strA B;
if(test){ // some amount of work is required to get the members of B
B = func1(...);
} else { // map the arguments to a structure
B.a = a; // the original arguments passed by constant reference
B.v = v;
};
return B;
};
int main(){
int a;
VectorXd v;
bool test;
strA B;
B = func3(a,v,test);
func2(B.a, B.v);
return 0;
}
In the case where test==true
(obviously) no problem for keeping the structure B and the arguments a and v as those entities are needed. However, when test==false
the alternative is just copying in a structure B the original arguments a and v (which are several large vectors in my application). Is there a cleaner approach or should I stick with the first? By the way, I am bothering with this as this piece of code appears in a loop, so I prefer avoiding copying the same code in several places.
Thank you!