How to define nullptr for supporting both C++03 and C++11? [duplicate]

假装没事ソ 提交于 2019-12-07 00:41:06

问题


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

回答1:


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.




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!