C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Explicitly specifying default arguments

From: Andrey Semashev <andrey.semashev_at_[hidden]>
Date: Thu, 2 Feb 2023 04:11:49 +0300
On 2/2/23 02:58, Zhihao Yuan wrote:
> On Wednesday, February 1st, 2023 at 7:39 AM, Andrey Semashev via Std-Proposals <std-proposals_at_[hidden]> wrote:
>
>>
>
>> In any case, my proposal is not about named arguments, it's about
>> simplifying passing the defaults, that's it.
>>
>
>
> I understand that you see a problem, but
> the outcome of the suggestion may need
> to be verified. Consider a code base where
> everything is passed via smart pointers.
> You see a function call like this:
>
> service->CreateConnection(nullptr, URL, nullptr, nullptr, payload, nullptr);
>
> Every parameter, presumably other than
> the first two, defaults to nullptr. Does
> it help, to change the call into
>
> service->CreateConnection(nullptr, URL, default, default, payload, default);
>
> ?
>
> It looks like "explicit default" looks
> equally good or bad compared to its prior
> arts.

If CreateConnection truly does need pointers as these arguments then
yes, explicit default does not improve the code very much, there's
little to improve as is. Although I would still prefer explicit default
for the reasons I described earlier - if you ever want to change the
default values to something other than nullptrs, it is much easier to do
if you're using explicit default.

But if you're using pointers (or, as another often used alternative,
std::optional) as a means to pass optional arguments which would
otherwise have reasonable defaults, then explicit default can be a
significant improvement.

  void close_connection(int code,
    const char* reason = nullptr,
    const std::vector< header >* extra_headers = nullptr)
  {
    // This allows nullptr as the default "keyword" at the call sites.
    // But it adds a runtime overhead.
    if (!reason)
      reason = "OK";

    ...
  }

  std::vector< header > extra_headers{ ... };
  service->close_connection(200, nullptr, &extra_headers);

vs.:

  void close_connection(int code,
    const char* reason = "OK",
    std::vector< header > extra_headers = {})
  {
    // No check needed here, just use reason and extra_headers
    // without checking
    ...
  }

  service->close_connection(200, default, { ... });

Received on 2023-02-02 01:11:55