When reading codes, we will find some functions like this.
g_spawn_async(NULL, new_argv, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, NULL);
I think nobody can figure out what is the meaning of every parameter. In order to understand the code, we have to find the declaration of the function.
gboolean g_spawn_async (const gchar *working_directory,
gchar **argv,
gchar **envp,
GSpawnFlags flags,
GSpawnChildSetupFunc child_setup,
gpointer user_data,
GPid *child_pid,
GError **error);
How can we call a function like the following format in C++?
g_spawn_async(working_directory=NULL,
argv=new_argv,
envp=NULL,
flags=G_SPAWN_SEARCH_PATH,
child_setup=NULL,
user_data=NULL,
child_pid=NULL,
error=NULL);
I think this one will be more readable and I can understand the code without looking for the declaration of the function.
I know Python can do this. How can C++ do this?
C++ doesn't support this natively, so you can't do it with just any old existing function. If you're creating your own API though, you can use what's called the Named Parameter Idiom to emulate it. The example from the link:
File f = OpenFile("foo.txt")
.readonly()
.createIfNotExist()
.appendWhenWriting()
.blockSize(1024)
.unbuffered()
.exclusiveAccess();
This is not possible in C or C++.
I understand your pains with this. I personally think that it is a sign of bad design to have a function take over 9000 arguments, especially if most of them are NULL
or placeholder values. Many POSIX-standardized functions for example take some kind of struct
that accumulates all necessary values into one, easy to understand argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With