Feb 9, 2016

[C++] inline namespace compile time replacement trick.

Curious Namespace Trick

tl;dr


 

  // global namespace
  void add_() {}
  void dot_() {add();}

  //i.e. g++ -DPLATFORM=arm
  inline namespace PLATFORM { void add() {add_();} }  //inject PLATFORM namespace, PLATFORM will be replaced during compile time preprocessor
  inline namespace PLATFORM { void dot() {dot_();} }  //inject PLATFORM namespace, PLATFORM will be replaced during compile time preprocessor
  
  // PLATFORM specific namespace
  namespace arm {
    void add_() {
      // very fast arm code
    }
  }

It is pretty neat, as:

  • Common/platform specific functions reside in the correct namespaces; 
  • Different platform can override different sets of functions seamlessly; 
  • Same trick works with template functions; 
  • And with template type definitions (via C++ 11 using syntax); 
  • Common implementations are still available in the original namespace to test again platform-specific code;

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.