码迷,mamicode.com
首页 > 其他好文 > 详细

FALSE_IT

时间:2017-07-22 09:40:35      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:pre   data   使用   function   pos   .text   ddc   顺序   proc   

本文讲一个实用的语法糖(suger),很不错,攻克了我实际工作中的问题。

如果你写了这样一个类:

class Executor {
  int step1();
  void step2();
  int step3();
}

#define FAIL -1

int main() {
  // 使用Executor。调用顺序必须是123
  Executor exec;
  if (FAIL == exec.step1()) {
       log(‘error‘);
  } else {
      exec.step2();   // 不能通过if调用,由于返回值是void
      if (FAIL == exec.step3()) {
         log(‘error‘);
      }
  }
 }

就由于一个void返回,让代码一下子别扭了,丑不丑?
如果能这样写该多好:

  Executor exec;
  if (FAIL == exec.step1()) {
       log(‘error‘);
  } else if (FAIL == exec.step2()) {
       log(‘error‘);
  } else if (FAIL == exec.step3()) {
       log(‘error‘);
  }

事实上办法是有的。仅仅须要写这样一个宏:

\#define FALSE_IT(stmt) ({ (stmt); false; })
  Executor exec;
  if (SUCCESS == exec.step1()) {
       log(‘error‘);
  } else if (FALSE_IT(exec.step2()) {   // 应用FALSE_IT宏
       log(‘error‘);  // won‘t be here
  } else if (FAIL == exec.step3()) {
       log(‘error‘);
  }

美丽不!

本方法来自阿里巴巴 OceanBase团队 @符风 同学。

FALSE_IT

标签:pre   data   使用   function   pos   .text   ddc   顺序   proc   

原文地址:http://www.cnblogs.com/slgkaifa/p/7220314.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!