What are Namespace Aliases

beginner c++11

Related: Namespaces

In C++ namespaces help avoid naming conflicts between symbols (variables, functions, and classes). Sometimes you may want to use a library from a third party but their namespace is bothersome to type or conflicts with one of your own. For this you can create a namespace alias. Here’s an example:

#include <iostream>

// Declare our own namespace
namespace robs_great_math_library {
  int add(int a, int b) {
    return a + b;
  }
}

// Create a namespace alias
namespace m = robs_great_math_library;

int main() {
  // Use the namespace alias we created
  std::cout << m::add(40, 2) << "\n";
  // We can still use the original name as well
  std::cout << robs_great_math_library::add(984, 737) << "\n";
}
42
1721


For more C++ By Example, click here.