Last active
March 16, 2018 22:44
-
-
Save cgbeutler/12c4b9619953c621eb845d0a460ad22c to your computer and use it in GitHub Desktop.
Null coalescense in C++ a bit like in C#, but admittedly not as good.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
#define Q(a, b) ([&](){ auto val = (a); if (val) (val->b); }()); | |
#define QQ(a, b) ([&](){ auto val = (a); return ((val) == NULL ? (b) : (val)); }()) | |
class A { | |
public: void sayHello() { cout << "Hello World\n"; } | |
}; | |
int main() | |
{ | |
A* nullPtr = NULL; | |
A* goodPtr = new A(); | |
Q( goodPtr,sayHello() ); | |
Q( nullPtr,sayHello() ); | |
QQ( nullPtr, goodPtr )->sayHello(); | |
QQ( goodPtr, nullPtr )->sayHello(); | |
QQ( nullPtr, QQ( nullPtr, QQ( nullPtr, goodPtr ) ) )->sayHello(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Q is like the C# 'maybeNullObj.?member'
QQ is like the C# 'maybeNull ?? backup'
NOTE: Q does not return anything, so cannot stack.