I am developing a project using C++98 . So I have no "nullptr". Of course I do a static code analysis for the source code in my project. From that I got many messages regarding the usage of 0 in assignments and comparisons. All messages are related to "different types". I started to add suffixes to 0, to define some correct types. But this is not possible for all build in data types. And especially not for pointers (Yes, raw pointer).
I then came up with the following template:
template <typename T>
const T null(void)
{
return static_cast<T>(0);
}
With that I get no more warnings regarding mixing up types. I can write for example:
typedef unsigned char uchar;
. . .
uchar someVariable = null<uchar>();
SomeComplexClass *someComplexClass = null<SomeComplexClass *>();
. . .
if (null<SomeComplexClass *>() == someComplexClass)
{
. . .
}
You may ask, omg, what is this nonesense. But being a Functional Safety Expert and working in the automotive industry, I am getting more and more cautios, even in small hobby home projects, like the above.
After reading Scott Meyers "Effective Modern C++", especially "Item 1: Understand template type deduction.", I am not any longer sure, if this template will work in any case. The compiler (gcc, raspbian) does of course always remove this stuff and replaces it with plain 0 in the object code. But
- Will the syntax be always OK?
- For any type?
- What about the constness?
- Any other solution?
I even have concerns regarding "nullptr". I think I am getting a little paranoid :-)