Есть ли в любом случае заполнить структуру более коротким кодом?

Мне нужно заполнить атрибуты х и у структуры. Учитывая, что у меня много членов (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);

Спасибо

1

Решение

Как это может быть

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");

Я не знаю что Whatever должно быть, но вы можете понять это. Может быть, даже сделать это шаблонным типом.

9

Другие решения

Ну, хотя не меньше инструкций, по крайней мере меньше нажатий клавиш и несколько легче для чтения:

#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
6

И C, и C ++ имеют агрегатную инициализацию: показывает стиль C: 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;
}
3
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector