简体   繁体   中英

C++: Combination of default parameters

I have a function that takes up to 4 arguments, all of them optional. Also, all arguments have default values, and the user can specify whichever combination of arguments he wants.

So if I have this:

void func (const A &a = A(), const B &b = B(), const C &c = C(), const D &d = D());

The user can use it as func(A(), B()) but not as func(B(), C()) .

Is there any way to allow every argument combination without having to create a bunch of overloads? (In this case it would be 8)

I have seen problems like this particularly when you're dealing with a big and old codebase. The best solution would be to redesign things so that you don't end up with such a problem, but I understand that sometimes you are under pressure and you have to make do with minimal changes.

For something like that, I would recommend creating a class that would encapsulate the parameters for that function. And that class would have the Builder design pattern:

https://en.wikipedia.org/wiki/Builder_pattern

So that you would have flexibility in which parameters you would pass.

In the example you gave, you could have something like this:

class FuncParams
{
  public:
     A& getA();
     B& getB();
     C& getC();
     D& getD();

     class FuncParamsBuilder
     {
         FuncParamsBuilder& setA(A& a);
         FuncParamsBuilder& setB(B& b);
         FuncParamsBuilder& setC(C& c);
         FuncParamsBuilder& setD(D& d);
         FuncParams *build();
     }

     static FuncParamsBuilder& builder();
}

Then, your function call would be just:

void func(FuncParams *params);

And you could call it this way:

func(FuncParams::builder().setA(a).setC(c).build());

Notice that this is not a perfect way to code this: you should adapt the code snippets above to fit better what you're trying to do. You may also think if you want to use pointers, references, or, even better, smart pointers such as unique_ptr objects. I hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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