【问题标题】:How to prevent repeating long rvalue如何防止重复长右值
【发布时间】:2016-05-22 11:06:56
【问题描述】:
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 来防止重复长右值。有没有更好的替代方法来做到这一点?

【问题讨论】:

  • 你知道什么是函数吗?如果是这样,为什么不编写一个函数来完成公式所需的计算?
  • int formula(int x,int y, int z, int w) { return x+y*z%w; }

标签: c++ coding-style rvalue


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-13
    • 2017-12-25
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    相关资源
    最近更新 更多