0

I am trying to write a managed C++ (aka C++/CLI) library that links to a third-party native C++ library. The third-party library's header files contain constructor definitions that use the nullptr keyword. My managed project fails to compile because the managed compiler defines nullptr to mean the managed null reference, whereas the third-party uses it to mean the native/un-managed null pointer. How can I work around this problem without modifying the third-party library's header file?

For reference on nullptr vs __nullptr, see: https://msdn.microsoft.com/en-us/library/4ex65770.aspx

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Will Rogers
  • 431
  • 1
  • 5
  • 14
  • 2
    You got a good answer. Taming your #includes is pretty important, striving to minimize the exposure is always important when you interop with foreign code. Just #define _ALLOW_KEYWORD_MACROS – Hans Passant Mar 05 '16 at 00:05

1 Answers1

5

C++/CLI supports the same preprocessor directives as C++, right? How about this terrible hack:

#define _ALLOW_KEYWORD_MACROS
#define nullptr __nullptr
#include "header.h"
#undef nullptr
Matti Virkkunen
  • 63,558
  • 9
  • 127
  • 159
  • I should have mentioned; a colleague already suggested that, but it doesn't work: `#error: The C++ Standard Library forbids macroizing keywords.` – Will Rogers Mar 04 '16 at 23:59
  • ...apparently there is a way to turn those errors off. Not entirely sure if that's a good idea though. – Matti Virkkunen Mar 05 '16 at 00:17
  • 2
    Well, not so sure you can blame Microsoft for this problem. It is that doggone ISO committee that added so many keywords to C++11 that were already used in C++/CLI. Like nullptr, enum class, override, final. Pioneers have arrows in their back. – Hans Passant Mar 05 '16 at 10:38
  • @Matti, you should just add `#define _ALLOW_KEYWORD_MACROS` as Hans commented on the question (I'm saying it here since you probably wouldn't notice it on the question). – Lucas Trzesniewski Mar 05 '16 at 11:02
  • @HansPassant If C++/CLI was C++, which means it doesn't change the meaning of perfectly valid code, for example by adding keywords and the like, there wouldn't have been any problem. (And the only other one of that list which might have a different meaning in C++ than in C++/CLI is `enum class`, as far as I know... – Deduplicator Mar 05 '16 at 12:57
  • Thanks. That does seem to work. Appears you can `#undef _ALLOW_KEYWORD_MACROS` afterward, too, although I'm not sure the exact semantics of that. – Will Rogers Mar 07 '16 at 13:38