Hi Filip,
In Rust there's an operator for error propagation from Result<T, E> types, it works something like foo()?.bar()?.baz()? etc, either unwrapping or returning the error value at every step. There is a paper about adding an operator with this functionality to C++ https://wg21.link/p2561r2. The other thing that comes to mind are monadic operators in general. I don't like the try/else/catch syntax here and I think there are probably better ways of improving the ergonomics here.

Cheers,
Jeremy



On Sun, Feb 16, 2025 at 10:53 AM Filip via Std-Proposals <std-proposals@lists.isocpp.org> wrote:
Hi everyone,
I want to present to you possible new syntax that would allow for an easy improvement of both safety and user experience with any pointer/optional type.

We usually need to check many times the validity of an object, which is done with an:
if(wrapperType) // use wrapper
I frequently use code like:
return ptrType->get(0)->getParamsPtr()->getName();

With multiple sub wrappers or returned pointers I would love to be simply to reuse try keyword in the following way:

try return ptrType->optType.otherWrapper.value;
else return defaultValue;

In this example try keyword would check if every but last element is castable to bool, allows for an access with either . or ->
Then it would cast element by element in this statement and only go to the next element when the cast would succeed and return true.

Possibly single try could also be used with a function like:
try ptrType->returnedFunc();

The function would be executed only if pointer is not null.
It could also allow for a bit more complex syntax with catches, however it would then expand the meaning to also catch exceptions:

try return ptrType->value;
else return defaultValue;
catch (exception e) return exceptionValue;

Equivalent to wrapping entire try else with try catch.

Cheers, Filip
--
Std-Proposals mailing list
Std-Proposals@lists.isocpp.org
https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals