what came before:
- modern C++: function returns true / false, and a value or error message
- modern C++: write my own function that returns true / false, and a value or error message
C++ has released a new feature: return value parameter binding. It's a somewhat obscure name (some say: just like C++ itself ). Here is the short version of what it gives us:
A function (or member), traditionally, could return 1 "return value". Now, this value can be several things, captured in a class. And you can run a method of that return value while calling the function.
Example: you can have a parser function, that returns
- the parsed values (several things)
- and it can return a boolean success / failure at the same time. (so you can use if (myfunc() ... )
I've implemented this in a GPS message parser I wrote.
Original user code: the function returns a bool, and the data is returned via the i/o parameter o)
std::string reply = "$GPGLL,5051.83778,N,00422.55809,S,185427.150,V,N*4F";
nmea::gll o;
if (nmea::gll::from_data(reply, o)) { // data exchanged via an in/out parameter
// do stuff
}
With return value parameter binding: all outputs are returned: data and status. And the if makes a decision on that status.
std::string reply = "$GPGLL,5051.83778,N,00422.55809,S,185427.150,V,N*4F";
if (auto [result, success] = nmea::gll::from_data(reply)) {
// do stuff. result is the same object as o in the original code.
}
Spectacular? Maybe yes:
getting results as return values is neater than getting results via pointers or reference i/o parameters. And we don't have to choose between returning a status or a data set. We can do both.
In this example, the parsed value is available as the bound parameter result. And we call the result's function operator bool() (the if clause does).
This means that we can call the function and
- decide what to do based on success/failure: the if statement
- receive the results too, in our result "variable" (it's actually a bound parameter)
If you're interested in how this is coded, and how it's handled, leave a comment. The code is published on github.