Skip to main content
 首页 » 编程设计

c++之将两个具有相反操作数的函数重构为一个

2024年06月20日46arxive

我想重构以下 2 个函数,以便逻辑位于一个具有一个参数的函数中:

void zoom_in() { 
  object.zoom_factor *= 2; 
  object.width /= 2; 
  object.height /= 2; 
} 
 
void zoom_out() { 
  object.zoom_factor /= 2; 
  object.width *= 2; 
  object.height *= 2; 
} 

我尝试做的事情:

void zoom_in() { 
  zoom_helper(true); 
} 
 
void zoom_out() { 
  zoom_helper(false); 
} 
 
void zoom_helper(bool in) { 
  float factor = (in ? 2 : .5); 
  object.zoom_factor *= factor; 
  object.width /= factor; 
  object.height /= factor; 
} 

但是我宁愿让 factorint。我可以干净地重构这段代码吗?

请您参考如下方法:

您可以使用函数对象数组:

void zoom_helper(bool in) { 
    static const std::function<void(int&)> mul = [](int& x) { x *= 2; }; 
    static const std::function<void(int&)> div = [](int& x) { x /= 2; }; 
    static const auto update[2] = { div, mul }; 
    update[in](object.zoom_factor); 
    update[!in](object.width); 
    update[!in](object.height); 
} 

不过,我认为这没有多大好处,而且除了好玩之外,我个人也不会写这篇文章。