showing the arguments' name passed to a function

Hello,

Is is possible to show the argument's name when passing them to a function in c++.
For instance in python you can do this (this is a random example)
 
myStuff(numberOfBooks=5, numberOfPens=3)

You can identify inmediatly the arguments without having to read the documentation or hover over the function for intelisens to give a hint.
Otherwise if you just read myStuff(5, 3) you can't really tell what they are.

thx,
R
C++ does not allow you to specify the arguments by name like that, but I know there are some IDEs that will show the names even though they are not present in the code.

You can do something similar by taking a struct as argument and use designated initializers which was added in C++20.

1
2
3
4
5
6
7
8
9
10
11
12
// define a struct to hold all "arguments"
struct MyStuffArgs
{
    int numberOfBooks;
    int numberOfPens;
};

// declare the function
void myStuff(MyStuffArgs);

// call the function
myStuff({.numberOfBooks=5, .numberOfPens=3});
Last edited on
cool, thanks peter87.
While the designated initializers (which C has had for a while now and has finally been added to C++) are the correct tool for the job, historically there have been other hacks to get the job done.

My favorite is called “the named parameter idiom”. I have used it successfully (and still do!) on many, many projects.

The C++ FAQ goes into detail (and gives a nice example right at the outset) better than I care to right now:

https://isocpp.org/wiki/faq/ctors#named-parameter-idiom
Topic archived. No new replies allowed.