r/cpp • • Apr 19 '20

Default function arguments are the devil

https://quuxplusone.github.io/blog/2020/04/18/default-function-arguments-are-the-devil/
90 Upvotes

149 comments sorted by

View all comments

96

u/fransinvodka Apr 19 '20

I think default arguments are actually useful, but they lack one important, complement feature: Named Arguments.

Sometimes, a set of overloads works just fine. Some others you can just let the user name the ones they really need. I just like the way Python solved this.

I know there's problems implementing this feature into the language due to the declaration-definition nature of C++ functions, but I really think the ultimate fix to default arguments are named arguments.

34

u/qoning Apr 19 '20

100%

nothing worse than having an elegant function and having to list all default arguments in order to change just the last one.

5

u/Sander_Bouwhuis Apr 20 '20

100% + 100%!

Totally agree. Also, refactoring is hell.

10

u/Raknarg Apr 19 '20

If there's one thing I love about Python, it's the argument handling. Being able to package around and zip/unzip collections of positional/keyword arguments is very handy and make it very easy to compartmentalize functions and form general solutions. I prefer functional style programming wherever possible and this makes it a lot smoother. Currently the only way to do it is with variadic templates which are much more limited and clunky as hell, or explicitly by passing data structures with arguments, but the data structure way tightly couples my argument lists to those types, which is annoying.

3

u/Sander_Bouwhuis Apr 20 '20

Soooooooooooooooooooooooo want that feature!!!

5

u/ilep Apr 19 '20 edited Apr 19 '20

I would argue that overloading is the "C++ way".

I imagine supporting both polymorphism and backwards compatibility with C otherwise could be tricky: types and their order are what define which function is called and names don't exist during runtime in C++. Having both strong typing and late binding would get really complicated otherwise.

Also adding some strange name-based lookup might cause unacceptable runtime-overhead for many. So I don't see this coming ever if you don't have some runtime compiler as well sorting out what function you are calling.

3

u/_Js_Kc_ Apr 19 '20

I think if you tried to implement this feature in a way that it magically applies to all existing functions retroactively, you'd end up with a bad solution.

But it could certainly be implemented in such a way that a function declaration explicitly opts in to using named arguments. In that case, new overload resolution rules can be written that make sense for named arguments. I don't think it would differ much from the way positional arguments work, except that not the order of arguments, but the names present would dictate which overload gets picked. In the polymorphic case, overload resolution for positional arguments is based on the pointer or reference's static type, and I don't see why this should change with named arguments, so why would there be any (additional) runtime overhead? Of course, names should remain purely a compile-time concept.

Don't worry about C, just forbid named arguments for extern "C" functions. Make it an opt-in feature, with unambiguous (i.e. cannot be confused with positional arguments) syntax at both the function declaration and the call site. Whether named arguments are appropriate should be decided by the function's author.

3

u/fransinvodka Apr 19 '20

The thing is C++ has a problem with default arguments. I'm not proposing how the solution should be implemented (I don't think I have that much knowledge), but rather saying that it would be the best solution out of all of them.

We can't remove default arguments from the language, and they have clear problems that lead some people to not use them at all. They have some huge advantages, but I think they lack that extra bit to get the most out of them.

→ More replies (11)

7

u/Ameisen vemips, avr, rendering, systems Apr 19 '20 edited Apr 19 '20

IIRC, previous named argument proposals have been rejected.

Why can we not just literally copy C#'s implementation?

IIRC, it was rejected because declaration parameter names don't have to match the definition, or even exist... but I don't see that as a problem. If the declaration doesn't have names, you can't use them with that declaration. Problem solved. Only thing left is if both the declaration and definition are in scope with different names.

Presently, argument names in declarations are ignored, we'd have to make them semantically meaningful.

I suggest that if there is a name mismatch between declarations/definitions of a parameter, it cannot be named, OR it can be named with either if those names are not further ambiguous in regards to other parameters. The former is simpler to specify, the latter is more useful (poor example, but think a glm vec3 function where the first argument could be x or r).

3

u/SeanMiddleditch Apr 20 '20

Why can we not just literally copy C#'s implementation?

Because C++ isn't C#. :) There's lots of designs that work well in other languages that - for a variety of reasons - can't work in C++.

That said, I don't think anyone has yet put in a formal proposal for the work-around I've been evangelizing. Namely, opting a function declaration's parameter into being nameable (which solves the source-compatibility issue, gives us mandatory positional arguments, allows named parameters, and can address the multi-declaration issues in a back-compatible way). For syntax, I also think we should use something similar to designated initializers, which makes similar syntaxes work for initializing an aggregate or calling a function (and hence unlocks designated initializers for constructors).

e.g.,

// declare
void function(int unnamed, float position, char .named, int .also_named);

// use
function(1, 2.f, .named =  'c', .also_named = 4);

// ILLEGAL redeclaration (different names, diagnostic optional)
void function(int a, float b, char .c, int .d);

// LEGAL different overload
void function(int a, int b, int .c, int.d);

This might also open up some options for mandatory-names for some parameters, e.g. using ..identifier.

4

u/Ameisen vemips, avr, rendering, systems Apr 20 '20

That looks like you're trying to access a member of a type, though.

0

u/[deleted] Apr 19 '20

[removed] — view removed comment

5

u/[deleted] Apr 19 '20 edited Apr 19 '20

[removed] — view removed comment

2

u/infectedapricot Apr 20 '20 edited Apr 20 '20

Declaration:

struct Params {
    int widgetCount = 0;
    int blartleCount = 8;
    std::string description = "elephant";
};
void foo(Params params);

Use:

OtherModule::Params fooParams;
fooParams.blartleCount = 2;
foo(std::move(fooParams));

Pros:

  • Arguments are named.
  • Can have defaults for everything.
  • No overloading trickiness.
  • Can have basic (BASIC!) utility methods on parameters struct.
  • Sometimes it's useful to forward the whole parameters struct on to some other function ("but that means you should be using a class in the first place" - yes, sometimes it does, but not always).
  • In your IDE you get autocomplete for the parameters when you type params.

Cons:

  • Takes up an extra two lines of code (an extra one really, because often if there are a lot of parameters it's actually nice to separate setting them from calling the function).
  • Get objections from well-meaning programmers blindly following rules without understanding them: "But classes need to have all their members private with get/set accessors (but a massive massive list of unnamed parameters is OK)".

On balance, usually only worth it when there are quite a few parameters, maybe at least four.

Edit: Just noticed that /u/jbandela suggested the same thing, and added named initializers (not sure about that though).

4

u/serviscope_minor Apr 21 '20

Takes up an extra two lines of code

foo([]{Parameters p; p.blartleCount=2; return p;}());

Obviously that's much clearer!

1

u/NotMyRealNameObv Apr 19 '20

Have fun renaming a function argument name in your library if named arguments are added to the language.

Also, if you use strong types, it can be emulated using argument types instead of argument names.

2

u/Wouter-van-Ooijen Apr 19 '20

Not if you have multiple arguments of the same type. Yes, you can force the user to specify different types for int x and int y, but the implementations I have seen are ugly.

→ More replies (1)

1

u/fransinvodka Apr 19 '20

The problem with strong types is the pollution of the global namespace. If you use them in your program, it's okay. No other user is supposed to use them but yourself. With libraries it's another whole strory. I'm pretty sure the user doesn't want the identifier [nN]ame, for example, in the global namespace.

I'm not aware of a library that doesn't pollute the global namespace and, at the same time, provides that syntactic sugar of strong types. That hints me that a language-level feature is needed there.

8

u/NotMyRealNameObv Apr 19 '20

Why would the strong type have to be in the global namespace?

1

u/fransinvodka Apr 19 '20

Let me be clearer. Suppose I want my function to be called with a seed, so the user would do something like libns::func(Seed{user_seed}, ...), but if I define the strong type inside the library's namespace, the user then must do libns::func(libns::Seed{user_seed}, ...), which we can agree is not that aesthetic as we'd like. The only solution would then be defining it in the global namespace, and that's what I meant.

Maybe there's a workaround I'm not aware of, haven't gone too deep into strong typing

4

u/NotMyRealNameObv Apr 19 '20
using libns::Seed;
libns::func(Seed{user_seed}, ...);

And if user_seed is already of the correct type, you just get

libns::func(user_seed);

The library author should never force a polluted global namespace on the end user.

→ More replies (1)

1

u/hedayatvk Apr 19 '20

Well, actually you can use Boost Parameter library to have named arguments in C++:
https://www.boost.org/doc/libs/1_72_0/libs/parameter/doc/html/index.html

8

u/fransinvodka Apr 19 '20

That library, although being really cool and awesome, is quite heavy and not-so-easy to use in the beginning. I would use it in my personal program if I feel like I need functions with tons of arguments, but no way I would add it to my library as a dependency unless really really needed (for example, a library of machine learning).

I'd just like to have a language-level feature instead of a monster library that's quite hard to use

2

u/hedayatvk Apr 20 '20

Yeah, I see :) Just wanted to mention the possibility. I've not used it myself too.