Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can we call a function with "parameter=value" in C++?

Tags:

c++

c

function

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?

like image 469
Hank Avatar asked Aug 21 '13 15:08

Hank


2 Answers

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();
like image 96
Mark Ransom Avatar answered Sep 23 '22 08:09

Mark Ransom


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.

like image 39
arne Avatar answered Sep 24 '22 08:09

arne