Reputation: 5840
i want to write a function which takes in a vector of objects and name of one of their property. then it will do some manipulation based on the values of that property of the objects.finally will return an object.
eg.
class A{
Point center;
int length;
...
...
};
class B{
Point position;
bool value;
...
...
};
now if we pass the function a vector of type A, it should manipulate the objects based on the value of center; if we pass the function a vector of type B, it should manipulate the objects based on values of position.
functiona(vector<T>,string property)
inside the function how can i access a property based in the passed string property??
EDIT: the 2nd property being string is just for illustration; i don't care what type it is
Upvotes: 1
Views: 238
Reputation:
Yes, it can be done using pointers-to-members. Example use:
#include <iostream>
#include <vector>
using namespace std;
class A {
public:
int a;
A(int x):a(x){}
};
class B {
public:
int b;
B(int x):b(x){}
};
template <typename T> int func(vector<T> data, int T::*pointer) {
int total = 0;
for (unsigned i = 0; i < data.size(); ++i) {
total += data[i].*pointer;
}
return total;
}
int main() {
vector<A> vec1;
vec1.push_back(A(123));
vec1.push_back(A(456));
vec1.push_back(A(789));
vector<B> vec2;
vec2.push_back(B(666));
vec2.push_back(B(666));
vec2.push_back(B(666));
cout << func(vec1, &A::a) << endl;
cout << func(vec2, &B::b) << endl;
return 0;
}
You declare a pointer-to-member as such: valueType class::*pointerName
, read adresses as such: &class::field
and use them like that: object.*pointerToMember
or pointerToObject->*pointerToMember
.
Upvotes: 1