如何防止重复长右值
How to prevent repeating long rvalue
int main() {
int x = 1, y = 2, z = 3, w = 4;
#define formula x + y * z % w
x++;
do_something1(formula);
y++;
do_something2(formula);
z++;
do_something3(formula);
w++;
do_something4(formula);
#undef formula
return 0;
}
我目前正在使用 #define
来防止重复长右值。有没有更好的替代方法来做到这一点?
使用lambda表达式:
int main() {
int x = 1, y = 2, z = 3, w = 4;
auto formula = [&] { return x + y * z % w; };
x++;
do_something1(formula());
y++;
do_something2(formula());
z++;
do_something3(formula());
w++;
do_something4(formula());
return 0;
}
int main() {
int x = 1, y = 2, z = 3, w = 4;
#define formula x + y * z % w
x++;
do_something1(formula);
y++;
do_something2(formula);
z++;
do_something3(formula);
w++;
do_something4(formula);
#undef formula
return 0;
}
我目前正在使用 #define
来防止重复长右值。有没有更好的替代方法来做到这一点?
使用lambda表达式:
int main() {
int x = 1, y = 2, z = 3, w = 4;
auto formula = [&] { return x + y * z % w; };
x++;
do_something1(formula());
y++;
do_something2(formula());
z++;
do_something3(formula());
w++;
do_something4(formula());
return 0;
}