Possible Duplicate:
“Backporting” nullptr to C++-pre-C++0x programs
How to define nullptr
for supporting both C++03 and C++11?
Does below code is compiled with both C++03 and C++11 compiles without change the meaning of nullptr in C++11 compiler?
#include <cstddef>
#if !defined(nullptr)
#define nullptr NULL
#endif
In C++11, nullptr
is of type nullptr_t
. One of its big advantages compared to NULL
(or to 0
would say Bjarne since he does not like macros) is that between these two functions:
void foo(char*);
void foo(int);
foo(nullptr)
will call the char*
overload but foo(NULL)
will call the int
overload. So your solution may work in most of the cases, but you may have errors with functions overload.
AFAIK you cannot automate from within the code the detection of nullptr
support.
In practice you can read that as “impossible”, it’s a pretty strong “AFAIK”.
The thing to do is therefore to use compiler-specific code and/or build command. For example, in each relevant source add a
#include <cpp/nullptr.h>
and in the build command adjust the include path so that for compiler with nullptr
support, this picks up an empty header, while for an old compiler that lacks nullptr
, it picks up a header that defines it à la Meyers (say).
And then test very thoroughly!
I call the general concept of having multiple versions of a header, with just one selected by the build command, a virtual header. It is possible to build a lot of machinery around that, including conventions that only make sense in a more general case. Happily it’s not necessary for this particular case, but perhaps worth to be aware of.
Summing up: making C++ source code do things magically is not the way to go here. Adding a bit of help at the build level seems about right. :-)
来源:https://stackoverflow.com/questions/10496824/how-to-define-nullptr-for-supporting-both-c03-and-c11