如何防止重复长rvalue

时间:2016-05-22 11:06:57

标签: c++ coding-style 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来防止重复长rvalue。有没有更好的替代方法呢?

1 个答案:

答案 0 :(得分:6)

使用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;
}