Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perfectly emulate nullptr

I got tired of waiting for compiler support of nullptr (gcc 4.6 does but it's so new few distributions support it).

So as a stop gap until nullptr is fully supported I decided to emulate it. There are two examples of emulation: one from here, and one from wikibooks.

Of note, neither implementation mentions an operator ==. However, without one, the following code will not compile.

int* ptr = nullptr;
assert( ptr == nullptr ); // error here: missing operator ==

Is this operator == error a compiler bug?
Is operator == (and !=, <, <=, etc) needed to more perfectly emulate nullptr?
What else is different between an emulated nullptr and the real deal?

like image 240
deft_code Avatar asked Jun 07 '11 17:06

deft_code


2 Answers

You compiled it with C++0x compiler that failed for unknown reason. It compiles fine in C++03.

like image 173
Yakov Galka Avatar answered Sep 28 '22 05:09

Yakov Galka


Yes, you should implement such a thing. I am, however, surprised that the implicit conversion operators aren't kicking in and allowing you to compare without providing an explicit operator.

template<typename T> bool operator==(T* ptr, nullptr_t null) {
    return ptr == 0;
}
template<typename C, typename R> bool operator==(R C::* ptr, nullptr_t null) {
    return ptr == 0;
}
// And the reverse
like image 39
Puppy Avatar answered Sep 28 '22 05:09

Puppy