是否可以将结构的成员变量作为参数传递

Is it possible to pass a struct's member variable as parameter

本文关键字:变量 参数传递 成员 结构 是否      更新时间:2023-10-16

我正在尝试将结构的成员变量与类相关联。这样当我创建一个新类时,我可以指定它与结构中的这个成员变量相关联。例如:

struct A {
int a;
int b;
};
static A a[2];
a[0].a = 1;
a[0].b = 2;
a[1].a = 3;
a[1].b = 4;
class foo {
public:
foo(int index, ???) {
c = a[index].???;  //Is it possible to define the 2nd parameter as a getter of struct A's member? So this line could resolve to either a[index].a or a[index].b?
}
private:
int c;
};

因此:

  • new foo(0, ???( 会将 c 设置为 1 ???给定 A::a
  • new foo(0, ???( 会将 c 设置为 2 ???引用 A::b
  • new foo(1, ???( 会将 c 设置为 3 ???以引用 A::a
  • 新的 foo(1, ???( 会将 c 设置为 4 ???以引用 A::b

是的,有可能,你需要传递一个数据成员指针:

#include <iostream>
struct A
{
int a;
int b;
};
static A a[2]
{
1, 2
,   3, 4
};
class foo
{
public: int c;
public:
foo(int const index, int A::* const p_field)
{
c = a[index].*p_field;
}
};
int main()
{
foo const f1(0, &A::a);
::std::cout << f1.c << ::std::endl;
foo const f2(0, &A::b);
::std::cout << f2.c << ::std::endl;
foo const f3(1, &A::a);
::std::cout << f3.c << ::std::endl;
foo const f4(1, &A::b);
::std::cout << f4.c << ::std::endl;
return 0;
}

在联机编译器中检查此代码

你有几个选择。如果你只想要整数(就像你发布的代码一样(,那么只需将整数作为参数传递给构造函数并传递给它正确的数字。

class foo {
public:
foo(int val) {
c = val
}
private:
int c;
};
int main() {
foo f(a[0].b);
}

或者,您可以引用整数。这样,如果一个更改,另一个也将:

class foo {
public:
foo(int &val) : c(val) { } //need to use an initialization list for this one
private:
int &c;
};
int main() {
foo f(a[0].b);
a[0].b = -1; //f.c will be -1 now as well
}

使用 VTT 答案中的数据成员指针是最直接的解决方案,但我经常发现成员指针和成员函数指针语法有点麻烦,我相信编译器很难优化。

对于这类事情,我更喜欢使用无状态的lambda。您可以将 lambda 传递给函数模板,然后编译器可以轻松优化它:

#include <iostream>
struct A {
int a;
int b;
};
static A a[2]{{1, 2}, {3, 4}};
class foo {
public:
int c;
public:
template<typename F>
foo(int index, F getter) { c = getter(a[index]); }
};
int main() {
auto agetter = [](const A& a){ return a.a; };
auto bgetter = [](const A& a){ return a.b; };
foo const f1(0, agetter);
std::cout << f1.c << "n";
foo const f2(0, bgetter);
std::cout << f2.c << "n";
foo const f3(1, agetter);
std::cout << f3.c << "n";
foo const f4(1, bgetter);
std::cout << f4.c << "n";
}