Reputation: 192
I need to fill the attributes x and y of a structure. Given that I have a lot of members (x,y...) and everyone of them have the same attributes (read, write etc.), are there anyways I can do this in a shorter way than this ?
features.x.Read = GetAttribute(node,"x","Read",HexValue);
features.x.Write = GetAttribute(node,"x","Write",HexValue);
features.x.address = GetAttribute(node,"x","address",HexValue);
features.x.value = GetAttribute(node,"x","value",HexValue);
features.y.Read = GetAttribute(node,"y","Read",HexValue);
features.y.Write = GetAttribute(node,"y","Write",HexValue);
features.y.address = GetAttribute(node,"y","address",HexValue);
features.y.value = GetAttribute(node,"y","value",HexValue);
Thank you
Upvotes: 1
Views: 229
Reputation: 393457
Both C and C++ have aggregate initialization: showing the C-style: http://ideone.com/EXKtCo
struct X
{
int some;
const char* really_long;
double and_annoying_variable_names;
};
int main()
{
struct X x = { 42, "hello world", 3.14 };
// reassign:
struct X y = { 0, "dummy", 0.0 };
x = y;
return 0;
}
Upvotes: 3
Reputation: 87932
Like this maybe
void set_members(Whatever& member, const char* name)
{
member.Read = GetAttribute(node, name, "Read", HexValue);
member.Write = GetAttribute(node, name, "Write", HexValue);
member.address = GetAttribute(node, name, "address", HexValue);
member.value = GetAttribute(node, name, "value", HexValue);
}
set_members(feature.x, "x");
set_members(feature.y, "y");
I don't know what Whatever
should be, but you can figure that out. Maybe even make it a templated type.
Upvotes: 9
Reputation: 122391
Well, while not fewer instructions, at least fewer keystrokes and somewhat easier to read:
#define FILL(a, b) features.a.b = GetAttribute(node,#a,#b,HexValue)
FILL(x, Read);
FILL(x, Write);
FILL(x, address);
FILL(x, value);
FILL(y, Read);
FILL(y, Write);
FILL(y, address);
FILL(y, value);
#undef FILL
Upvotes: 6