Feb 9, 2016

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

Curious Namespace Trick

tl;dr
#include

// output:
//  dmitry@t:~$ g++ func.cpp -DPLATFORM=common ; ./a.out
//  common add
//  dmitry@t:~$ g++ func.cpp -DPLATFORM=arm ; ./a.out
//  arm add

namespace project {
  // arm/math.h
  namespace arm {
    inline void add_() {printf("arm add\n");}  // try comment out
  }

  // math.h
  inline void add_() {
    //
    printf("common add\n");
    //
  } inline namespace PLATFORM {inline void add() {add_();}}


  inline void dot_() {
    //
    add();
    //
  } inline namespace PLATFORM {inline void dot() {dot_();}}
}

int main() {
 project::dot();
 return 1;
}

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.