C++ Logo

std-proposals

Advanced search

Re: Proposal: template function solution to Pythonic optional function arguments

From: codusnocturnus <codusnocturnus_at_[hidden]>
Date: Mon, 20 Jul 2020 21:26:20 +0000
‐‐‐‐‐‐‐ Original Message ‐‐‐‐‐‐‐
On Monday, July 20, 2020 1:43 PM, Jason McKesson via Std-Proposals <std-proposals_at_[hidden]> wrote:

> On Mon, Jul 20, 2020 at 2:23 PM codusnocturnus via Std-Proposals
> std-proposals_at_[hidden] wrote:
>
> > Having the code-bloat associated with defining and naming a struct, as well as pulling in std::optional all over the place to get the equivalent of named parameters is objectively terrible (I think you even questioned the viability), and, subjectively, it looks awful at the call site, too.
>
> Or, you could just not use named arguments. Broadly speaking, named
> arguments is only useful when you have a function that takes a lot of
> parameters (none of which have any logical grouping between them).
> Most functions generally take 5 or less. Named arguments become
> increasingly useful the more parameters a function takes.
>
> But if you can avoid having functions take large numbers of parameters
> to begin with, then you don't really need them.

Sure, a function with lots of (especially defaulted) parameters is usually a code smell, but not always.

That argument mostly only holds for greenfield and personal projects anyway. Some of us live in the world of (very dirty) brownfield projects, and named parameters would provide a much easier way to make legacy code more maintainable than trying to get budget to reach the perfect abstraction.

Named parameters make code easier to read in all cases for number of parameters > 1 (self-documenting, if you will).


...
> > would make function overloading and default parameters as useable in C++ as they were intended to be. These are features that distinguish C++ from C, but today (on this very thread) we have notable language experts actively campaigning against their use!
>
> We do? I've heard people say that default arguments should be avoided,
> but I've never heard any "notable language experts" saying that we
> should avoid function overloading in general.


I may have overstated and/or miscontextualized, but I'm pretty sure one of Arthur's suggestions involved "un-overloading" a function.
 (He's active here and at C++ conferences, so I consider him both notable and an expert.) Granted, that was not a general "don't overload" suggestion - more of a "don't inappropriately overload and then use defaults." I think poor use of default arguments is often related to function overloading, as this case points out.

""
Even better for your rapid-prototyping work:

    int draw(int param);
    int draw_with_mode(int param, int mode);

    draw_with_mode(1, -1);
""

Thanks,

Received on 2020-07-20 16:29:43