What does null mean?
Hi,
If you read this code, what do you think it does?
CameraMan cm( nullptr );
It could mean anything, right?
In a previous post I elaborated with ideas to prevent the explicit usage
of nullptr. Thanks for all the replies there by the way!
http://groups.google.com/group/comp.lang.c++.moderated/browse_thread/thread/02437f22744b051c
I experimented with it and came up with the following solution (if
you're not interested in reading code you can jump directly to the
question in the end).
#include <utility>
template<typename T, class NullT>
class NullNameAdapter
{
public:
// Use Perfect Forwarding to pass the parameter (except
// nullptr) as efficient as possible.
template<typename U>
NullNameAdapter( U&& u ) : t_(std::forward<U>(u)) {}
// Delete the constructor taking nullptr. Doing this
// is the essense of this adapter.
NullNameAdapter( std::nullptr_t ) = delete;
// This constructor is the replacement for the deleted
// std::nullptr_t constructor above.
NullNameAdapter( NullT ) : t_(nullptr) {}
// Conversion operator to be able to return the type
// easily.
operator T&() { return t_; }
private:
T t_;
};
const struct BadAngleType {} BAD_ANGLE;
typedef NullNameAdapter<int*, BadAngleType> AnglePtrNNA;
class CameraMan
{
public:
CameraMan( AnglePtrNNA angle ) : angle_(angle) {}
private:
int* angle_;
};
int main()
{
int* anglep = new int( 180 );
CameraMan a( anglep );
CameraMan b( BAD_ANGLE );
CameraMan c( nullptr ); // Won't compile. Good!
return 0;
}
I almost got it to work on a general basis. The only thing I didn't
manage to solve was the situation if you replace int* with
std::unique_ptr<int>. (If anyone feels tempted to solve it I would be
delighted)
Even if this could be solved I realize that it's quite a lot of
boilerplate code just to prevent the explicit nullptr, so I'm about to
abandon that strategy. I still think though, that the explicit nullptr
is troublesome so I want at least to come up with some coding guideline.
In C++ Coding Standards by Sutter & Alexandrescu there is the
recommendation Item 17 - Avoid magic numbers. It says that instead of
using 3.1415 explcitly in the code you should make a symbolic constant
out of it, like this.
const double PI = 3.1415;
My question is; would you all agree that nullptr is a magic number that
always should be replaced with a label like the following?
const std::nullptr_t BAD_ANGLE = nullptr;
Thanks,
Daniel
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]