Monday, July 24, 2017

C++11: Inline namespace

You can declare a namespace inline. This causes it’s symbols to be accessed as if they were contained in the enclosing namespace. Here is an example:

#include <iostream>
#define BOTTOM_VERSION 1
namespace Top {
#if BOTTOM_VERSION == 1
  inline 
#endif
 namespace Bottom_V1
 {
   const int v = 1;
 }
#if BOTTOM_VERSION == 2
  inline 
#endif
 namespace Bottom_V2
 {
   const int v = 2;
 }
}
int main()
{
  std::cout << Top::v            << " " << 
               Top::Bottom_V1::v << " " << 
               Top::Bottom_V2::v << std::endl;
  return 0;
}
// Output: 1 1 2
// If BOTTOM_VERSION is #defined as 2, then the output is: 2 1 2
Reference: https://isocpp.org/wiki/faq/cpp11-language#inline-namespace

No comments:

Post a Comment