First of all, I would like to say this is the first question I am asking on stackOverflow, so I apologize if I am not clear enough.
My question regards referring parametrically to a struct feature inside a function. I work in C++.
What I really want to achieve is to be able to sort a vector of struct objects (or class objects) based on a specific struct feature, which is given as a parameter. I also want to give the type of struct through a template, so some workarounds that deal with specific situations might not work in general.
I will show a simplistic example of what I mean.
Let's say, I have a struct called "human" with features: "age", "height", "weight".
Let's also assume that I have a vector of "human" objects called "mankind".
Here, let's say I want to make a function that can output to the screen each element's age, height or weight, depending on what I pass as a parameter.
The code below obviously doesn't work. I am asking for the proper way to do this.
struct human{
int age;
int height;
int weight;
};
void show(vector<human> &elements, int value){
for (int i=0; i<elements.size(); i++)
cout << elements[i].value << endl;
}
int main{
...
vector<human> mankind;
...
show(mankind, age);
show(mankind, height);
show(mankind, weight);
...
return 0;
}
I want to point out, that this example is a very simple case. Of course, I can make this work if I make separate functions for each feature or if I use a cheeky way, like passing a string "age" or "height" or "weight" as a parameter, checking it inside the function and having a completely separate case for each one.
However, such workarounds won't work in the general case of the problem, especially if I have many different types of structs (passed through a template T
and vector< T >
) and features.