Skip to content

Instantly share code, notes, and snippets.

@mooware
Last active December 16, 2015 06:29
Show Gist options
  • Save mooware/5392031 to your computer and use it in GitHub Desktop.
Save mooware/5392031 to your computer and use it in GitHub Desktop.
Implementation of the C++11 feature nullptr_t and an example of why it works better than the C #define NULL
struct nullptr_t
{
template <typename T>
operator T*() { return static_cast<T*>(0); }
};
nullptr_t nullptr;
#include <iostream>
const char *foo(int *) { return "ptr"; }
const char *foo(int) { return "int"; }
#define SIMPLE_NULL 0
#define PRINT(expr) std::cout << #expr ": " << expr << std::endl
int main()
{
PRINT(foo(0)); // "int"
PRINT(foo((int*)0)); // "ptr"
PRINT(foo(NULL)); // compile error in GCC 4.6.3, ambiguous call
PRINT(foo(SIMPLE_NULL)); // "int"
PRINT(foo(nullptr)); // "ptr"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment