Suppose I have a class as follows:
class Solution {
public:
std::vector<double> x;
}
Suppose I have a function as follows:
void function(Solution& sol) {
// do some calculations on the solution vector
}
Under some circumstances, I will want function to perform calculations directly using the vector x. However, under some circumstances I will want to perform calculations using another vector that is produced by a mapping of the vector x.
Give these possible circumstances, it makes sense to introduce an additional member to the class Solution, but in the first circumstance this additional member will simply refer to x, and in the second circumstance this additional member will itself be another std::vector that is determined by a mapping of some form.
So, ideally I could add a ctor to Solution that creates/defines a member named y either as a std::vector or as merely a reference to x. Then, my function could simply operate directly using y.
How might I do this?
You can define your function as:
And pass different vectors to it, depending on circumstances
Edit Using references in ctors
This way your
functionalways operates on the same reference, but you can control what data this reference refers to. Note thatxandyare now private — this ensures that these members are only used locally viafunction()method.