简体   繁体   English

重构:在子函数中委托友谊

[英]Refactoring : delegate friendship in sub-functions

I refactor a code where a class has a friend function doing a lot of stuff.我重构了一个代码,其中 class 有一个朋友 function 做了很多事情。

class Foo
{
  friend void do_something(Foo& foo);
};

void do_something(Foo& foo)
{
  // More than 2000 lines of ugly code
}

I would like to split the content of do_something in several small functions.我想将do_something的内容拆分成几个小函数。 Something looking like this:看起来像这样的东西:

void do_something(Foo& foo)
{
  if(case_1) do_1(foo);
  else if(case_2) do_2(foo);
  else if(case_3) do_3(foo);
  //...
}

Is there a design where I can transfert the friendship to the sub-fuctions do_x(Foo&) without having to declare them in the class, or something similar in order to split the code?有没有一种设计可以将友谊转移到子功能do_x(Foo&)而不必在 class 或类似的东西中声明它们来拆分代码?

Note: C++11 only注:仅限C++11

Note: I don't want to write the sub-functions as maccros注意:我不想把子函数写成宏

Instead of having do_something as function calling other sub-functions, I would suggest you to create an analogous class DoSomehting .我建议您创建一个类似的 class DoSomehting ,而不是将do_something作为 function 调用其他子函数。

Then you could declare this class as a friend with friend class DoSomehting;然后你可以将这个 class 声明为friend class DoSomehting; . . So these sub-functions could be its private methods.所以这些子函数可以是它的私有方法。 The method to call -- could be a public method named eg like void DoSomehting::process(Foo& foo) :调用的方法 -- 可以是一个名为void DoSomehting::process(Foo& foo)的公共方法:

class Foo
{
  friend class DoSomething;
};

class DoSomething
{
public:
    void process(Foo& foo)
    { 
        if(case_1) do_1(foo);
        else if(case_2) do_2(foo);
        else if(case_3) do_3(foo);
        //...
    }  

private:
    void do_1(Foo& foo);
    void do_2(Foo& foo);
    void do_3(Foo& foo);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM