反正有没有用更短的代码填充结构?

hlx*_*hlx 1 c c++

我需要填充结构的属性x和y.鉴于我有很多成员(x,y ...),并且每个人都有相同的属性(读,写等),无论如何我能以比这更短的方式做到这一点吗?

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);
Run Code Online (Sandbox Code Playgroud)

谢谢

joh*_*ohn 9

也许这样

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");
Run Code Online (Sandbox Code Playgroud)

我不知道Whatever应该是什么,但你可以搞清楚.甚至可能使它成为模板类型.


tro*_*foe 6

好吧,虽然说明少,但击键次数更少,更容易阅读:

#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
Run Code Online (Sandbox Code Playgroud)