Templatizing a function based on a class member?

Some background: I have a class, A, with members, B and C and D; I also have an array of A objects; I want to be able to have a function which takes said array and performs a certain calculation on either the B, C, or D members of each of the A objects, depending upon certain circumstances; I want to perform the same calculation regardless of which member is to be used in said calculation, such as always assigning the value 3 or multiplying the member's value by a cofactor of some sort.

My question, therefore, is: Would Anyone be kind enough to point Me in the direction of how I might do this using only one function be it a template or not?

Much appreciated in advance.
You are interested in C++'s pointer-to-member feature. Here's a small demo:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <vector>

struct A
{
    int B, C, D;
};

void f(std::vector<A> va, int A::*m)
{
	for(A &a : va)
	{
		std::cout << a.*m << std::endl;
	}
}

int main()
{
	std::vector<A> va =
	{
		{1, 2, 3},
		{4, 5, 6},
		{7, 8, 9}
	};
	f(va, &A::B);
	f(va, &A::D);
}
1
4
7
3
6
9
http://ideone.com/UCpXwI

There are pointers to data members, and pointers to member functions:
1
2
MemberType ClassName::*pointerName; //pointer to data member
ReturnType (ClassName::*pointerName)(ParameterTypes...); //pointer to member function 
In either case, to obtain the specific pointer you want, you write &ClassName::MemberName.

There are operators .* for direct access via pointer to member, and ->* for indirect access via pointer to member. For data members, it is simply instance.*pointerName or pInstance->*pointerName, and for functions, it is (instance.*pointerName)(args...); or (pInstance->*pointerName)(args...); pointerName can also be a parenthesized expression for dynamically selecting which pointer-to-member to use.
Last edited on
Topic archived. No new replies allowed.