Difference between usage and usage = for types?

Consider the following two using statements:

 using ::space1::space2::MyType; using MyType = ::space1::space2::MyType; 

After using , it seems that both methods allow us to use MyType directly (without any qualifiers).

So what's the difference between the two of these two?

+5
source share
3 answers

As the comment says, in the first case, you are actually exporting the name from the namespace to the one that contains the using declaration, while in the second case you define an alias in the namespace that contains using , which points to that particular name and its surrounding namespace .

As an example with the second expression, you can define aliases, such as the following:

 using Foo = Bar<MyClass>; template <class C> using Foo = Bar<C, MyClass>; 

While the first using statement cannot, it serves just to make the names available in different spaces than those that contain them.

See here for more information on using directives using declarations and aliases (types and templates).

+2
source

The first allows you to refer to a variable / type by its unqualified name.

The second declares a name of type new in the enclosing namespace.

+1
source

In addition to skypjack, a nice answer, there is another difference for entries when statemetns are used inside the class definition.

Inside the class definition, the using expression should introduce a member of the base class, while the type alias is still the type alias:

 namespace space1 { namespace space2 { class MyType {}; } } struct s1 { using ::space1::space2::MyType; // error MyType b; }; struct s2 { using MyType = ::space1::space2::MyType; // perfectly valid MyType a; }; 
+1
source

Source: https://habr.com/ru/post/1235062/


All Articles