views:

678

answers:

1

I saw that nullptr was implemented in Visual Studio 2010. I like the concept and want to start using it as soon as possible; however GCC does not support it yet. My code needs to run on both (but doesn't have to compile with other compilers).

Is there a way to "emulate" it? Something like:

#define nullptr NULL

(but obviously that wouldn't work well at all, I was simply showing what I meant).

+18  A: 

The Official proposal has a workaround -

const                        // this is a const object...
class {
public:
  template<class T>          // convertible to any type
    operator T*() const      // of null non-member
    { return 0; }            // pointer...
  template<class C, class T> // or any type of null
    operator T C::*() const  // member pointer...
    { return 0; }
private:
  void operator&() const;    // whose address can't be taken
} nullptr = {};              // and whose name is nullptr
N 1.1
Thanks. do you also know if there's a way to detect if `nullptr` is implemented, without relying on the version of __cplusplus (because technically I'm using C++0x, and nullptr isn't there)
nuzz
@nuzz: Then you aren't using C++0x. :)
Bill
Well, I'm using a part of C++0x ;)
nuzz
just keep a tab on compiler implementation status of c++0x.
N 1.1
I think nuzz's question is, can this be detected, so the code would use the built-in nullptr instead of the emulated one if implemented?
UncleBens
if nullptr has been implemented, `char *str = nullptr` wont throw any error.
N 1.1
To work with different compilers/versions, I would do something like what Boost does. Search the Boost headers for stuff like BOOST_WORKAROUND(__GNUC__, < 3). Long story short, differentiate between compilers by using the preprocessor.
nobar
@Uncle: especially because if it's implemented that workaround code won't work because `nullptr` is a keyword, I believe
Andreas Bonini
@Andreas: Exactly. You could use the preprocessor, but I'd imagine C++0x support is in a state of great flux, so you'd have to constantly keep an eye on what is and what isn't implemented in different compiler versions.
UncleBens