C++ Logo

std-proposals

Advanced search

Named params via anonymous struct and function aliases

From: Maciej Cencora <m.cencora_at_[hidden]>
Date: Mon, 29 Jul 2019 17:17:07 +0200
Hi,

here is an idea on how to support named parameters in backward compatible
way:

allow single anonymous struct definition inside func parameter signature:
void foo(struct { bool param1; int param2; })
{
  impl(param1, param2);
}

The signature:
void foo(struct { bool param1; int param2; })
 is equivalent to:
void foo(bool param1, int param2).

with the added benefit that it supports named parameters via designated
initializers:
foo({.param1 = false, .param2 = 10});
or
foo(false, 10);

Designated initialization rules could be relaxed for this specific case to
allow initializers be in different order than declared.

This won't brake existing code, and we can introduce named params for
existing API via function alias mechanism in backward compatible way:

assuming we have POSIX fopen:
int fopen(const char* pathname, const char* mode);

we standardize new function alias:
using fopen(struct { const char* pathname; const char* mode;}) =
fopen(pathname, mode);

and now user can do:
fopen("/my/file", "w")
or
fopen({.pathname = "/my/file", .mode = "w"});


Function alias mechanism could be re-used in many more scenarios (e.g.
during refactoring, when changing func name, or re-ordering parameters,
etc.).


Thoughts?

Regards,
Maciej

Received on 2019-07-29 10:19:16