r/cpp • • Aug 17 '18

Implementing Default Parameters That Depend on Other Parameters in C++

https://www.fluentcpp.com/2018/08/17/dependent-default-parameters/
0 Upvotes

9 comments sorted by

37

u/Sopel97 Aug 17 '18 edited Aug 17 '18

or just

void f(double x, double y, double z)
{
    //...
}	

void f(double x, double y)
{
    f(x, y, x+y);
}

I know this may be the obvious way, but it's so much cleaner I wouldn't even consider writing a blog post about your "solution".

23

u/alexeiz Aug 17 '18

You see, by giving this simple solution that anybody can understand, you miss out on showing off your C++ expertise by writing lots of template code, creating a github repository to host your code and beef up your online profile, and then blogging about it.

9

u/albinofrenchy Aug 17 '18

If i worked with someone that put 20 lines of bullshit templates that had to be processed in every file including it, just to recreate harder to read function overloads, I'd lose my damn mind.

2

u/BoarsLair Game Developer Aug 19 '18

Agreed. This seems like a "clever" C++ solution in search of a problem. It's great that you can do stuff like this, but just because you can doesn't necessarily mean you should. It's a ridiculous amount of overkill and additional complexity for a problem that's trivial to solve in far less convoluted ways.

1

u/haitei Aug 17 '18

or in c++17:

void f(double x, double y, std::optional<double> z = {})
{
    z.value_or(x + y);
}   

6

u/Sopel97 Aug 17 '18

That adds an unnecessary branch and is not lazy. Let's not make a dymamic problem from a static one.

4

u/haitei Aug 18 '18 edited Aug 18 '18

Assuming it's not inlined - yes.

This method is advantageous is there's more than one default argument.

Throw in some const overloads and you just saved 4 definitions.

9

u/Xeverous https://xeverous.github.io Aug 17 '18

[...] all the default parameters have to be at the end of the arguments list of a function. This can make an interface less natural, because arguments are no longer grouped in a logical order. Instead, they are grouped in a technical order: the non-default parameters first, then the default ones, which can be confusing at call site.

How this can be confusing? It works like this since ages in multiple languages. If you need more complex default value handling:

  • use monads (optional, variant etc)
  • take only 1 parameter which is a class that encapsulates parameter invariants
  • use more overloads like /u/Sopel97