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

僤鯓⒐⒋嵵緔 提交于 2019-12-05 03:14:20

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. :-)

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