成员变量包装器

可以使用std :: mem_fn存储和包装成员函数。成员变量包装器

在C中,您可以在成员变量上使用offsetof(...)粗略地包装成员变量(但仅限于某些类型)。

是否可以在C++中包装成员变量?什么是最干净的方式?

class X 

{

...

M m;

...

};

mem_var<M> xm = &X::m;

int main()

{

X x = ...;

M i = ...;

xm(x) = i; // same as x.m = i

cout << xm(x); // same as cout << x.m

}

回答:

是的,你可以做到这一点... std::mem_fn

struct B 

{

int x;

int y;

};

int main()

{

auto m = std::mem_fn(&B::y);

B b {0, 0};

m(b) = 4;

printf("%d %d\n", b.x, b.y); // prints 0 4

printf("%d\n", m(b)); // prints 4

return 0;

}

演示:http://ideone.com/40nI2

以上是 成员变量包装器 的全部内容, 来源链接: utcz.com/qa/260329.html

回到顶部