Namespace aliases

Namespace aliases allow the programmer to define an alternate name for a namespace.

They are commonly used as a convenient shortcut for long or deeply-nested namespaces.

Syntax

namespace alias_name = ns_name; (1)
namespace alias_name = ::ns_name; (2)
namespace alias_name = nested_name::ns_name; (3)

Explanation

The new alias alias_name provides an alternate method of accessing ns_name.

alias_name must be a name not previously used. alias_name is valid for the duration of the scope in which it is introduced.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
  
namespace foo {
    namespace bar {
         namespace baz {
             int qux = 42;
         }
    }
}
  
namespace fbz = foo::bar::baz;
  
int main()
{
    std::cout << fbz::qux << '\n';
}

Output:

1
 

See also

namespace declaration identifies a namespace
doc_CPP
2025-01-10 15:47:30
Comments
Leave a Comment

Please login to continue.