Is there a C++ equivalent for C# null coalescing operator? I am doing too many null checks in my code. So was looking for a way to reduce the amount of null code.
相关问题
- Sorting 3 numbers without branching [closed]
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- How to compile C++ code in GDB?
Just want to expand @Samuel Garcia's answer by generalising the template and adding helper macros to cut down on lambda boilerplate:
Using the macros, you can just:
I hope this helps.
How about this?
Using templates and C++11 lambdas. The first argument (left-hand side) is only evaluated once. The second argument (right-hand side) is only evaluated if the first is false (note that 'if' and '?' statically cast the provided expression to bool, and that pointers have 'explicit operator bool() const' that is equalivent to '!= nullptr')
Example of use
Will just print '0xf' in the console. Having to write a lambda for the rhs is a little bit of boilerplate
but it's the best that one can do if one lacks support by the language syntax.
There isn't a way to do this by default in C++, but you could write one:
in C# the ?? operator is defined as
So, the C++ method would look like
I just found this: The ?? operator aka the Null Coalescing Operator