Skip to content

Instantly share code, notes, and snippets.

@cgbeutler
Last active March 16, 2018 22:44
Show Gist options
  • Save cgbeutler/12c4b9619953c621eb845d0a460ad22c to your computer and use it in GitHub Desktop.
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.
#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();
}
@cgbeutler
Copy link
Author

cgbeutler commented Mar 16, 2018

Q is like the C# 'maybeNullObj.?member'
QQ is like the C# 'maybeNull ?? backup'
NOTE: Q does not return anything, so cannot stack.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment