如何将结构成员标识符传递给函数,以便该函数可以将操作应用于该指定成员?下面的代码示例应该突出显示我想要实现的目标。
struct _struct {
int a = 0;
int b = 0;
};
_struct test[5];
void printVar(int index, ??? member) {
// Print specified member at array element
printf(test[index].member);
};
int operation(??? member) {
// Some operation applied to specified member of all array elements
// eg. Averaging all the readings contained in test[].a
int total = 0;
for (int i = 0; i < 5; i++) {
total += test.member;
};
return total / 5;
};
我找到的最接近解决方案的描述在下面的链接中,虽然其应用原理是合理的,但它似乎不是最好的实现。 http://cplusplus.com/forum/beginner/45268/
答案 0 :(得分:3)
这就是“指向成员的指针”的用途。
struct _struct {
int a = 0;
int b = 0;
};
_struct test[5];
void printVar(int index, int _struct::* member) {
// Print specified member at array element
printf("%d\n",test[index].*member);
};
int operation(int _struct::* member) {
// Some operation applied to specified member of all array elements
// eg. Averaging all the readings contained in test[].a
int total = 0;
for (int i = 0; i < 5; i++) {
total += test[i].*member;
};
return total / 5;
};
int main(){
printVar(1,&_struct::b);
operation(&_struct::a);
return 0;
}
答案 1 :(得分:2)
如何传递一个 std::function
从给定的 _struct
返回所需的成员?像这样:
#include <functional> // for std::function
struct _struct {
int a = 0;
int b = 0;
};
_struct test[5];
void printVar(int index, std::function<int(const _struct&)> getMember) {
// Print specified member at array element
printf("%d\n", getMember(test[index])); // note: added missing "%d"
};
int operation(std::function<int(const _struct&)> getMember) {
// Some operation applied to specified member of all array elements
// eg. Averaging all the readings contained in test[].a
int total = 0;
for (int i = 0; i < 5; i++) {
total += getMember(test[i]); // note: added missing [i]
};
return total / 5;
};
你会像这样使用它:
int get_a(const _struct& s) { return s.a; }
int get_b(const _struct& s) { return s.b; }
int main()
{
test[0] = {0,1};
test[1] = {2,3};
test[2] = {4,5};
test[3] = {6,7};
test[4] = {8,9};
printVar(2, get_a); // prints value of test[2].a
printVar(4, get_b); // prints value of test[4].b
const int result_a = operation(get_a); // perform operation on the a members
const int result_b = operation(get_b); // perform operation on the b members
return 0;
}
或者,如果您熟悉 lambda,您可以使用它们来定义 get_a
和 get_b
,而不是让它们成为独立的函数:
int main()
{
test[0] = {0,1};
test[1] = {2,3};
test[2] = {4,5};
test[3] = {6,7};
test[4] = {8,9};
const auto get_a = [](const _struct& s) { return s.a; };
const auto get_b = [](const _struct& s) { return s.b; };
printVar(2, get_a); // prints value of test[2].a
printVar(4, get_b); // prints value of test[4].b
const int result_a = operation(get_a); // perform operation on the a members
const int result_b = operation(get_b); // perform operation on the b members
return 0;
}