有一种方法来应用一个函数给结构的每个成员在c ++中? [英] Is there a way of applying a function to each member of a struct in c++?

查看:108
本文介绍了有一种方法来应用一个函数给结构的每个成员在c ++中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您有一个简单的结构,例如:

You have a simple struct, say:

typedef struct rect
{
    int x;
    int y;
    int width;
    int height;
}
rect;

并且要将每个元素乘以一个因子。是否有一个更简洁的方式来执行这个操作,除了将每个成员乘以值?

And you want to multiply each element by a factor. Is there a more concise way of performing this operation, other than multiplying each member by the value?

推荐答案

编程获取结构的元素列表需要反射,C ++不支持。

Not really. Programatically obtaining a list of the elements of a struct requires reflection, which C++ does not support.

你的两个选项是给结构一个方法, - 然后在所有其他地方使用该方法,或手动模仿反射,例如通过给struct一个指向所有其他元素(构建在struct的构造函数中)的指针数组的另一个元素,然后循环执行缩放功能。

Your two options are to just give the struct a method that does this the long-winded way and then use that method in all other places, or to manually mimic reflection, for example by giving the struct another element which is an array of pointers to all of its other elements (built within the struct's constructor), and then looping over that to perform the scaling function.

这篇关于有一种方法来应用一个函数给结构的每个成员在c ++中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆