What are the differ开发者_开发百科ences between using
typedef Some::Nested::Namespace::TypeName TypeName;
or
using Some::Nested::Namespace::TypeName;
to provide the shorthand TypeName
in the local scope?
typedef
gives an alias name for the type.
typedef Some::Nested::Namespace::TypeName TypeName;
Once you do that, You can refer Some::Nested::Namespace::TypeName
just by saying TypeName
in the local namespace.
using declaration
makes the type visible in the current namespace.
using Some::Nested::Namespace::TypeName;
Imports the type in the current namespace.
In this case, using the either of the above you can refer Some::Nested::Namespace::TypeName
by just using TypeName
in the local namespace.
Using just brings declaration into the local scope, while typedef introduces a typedef-name. One difference between them is elaborated type specifiers, e.g.:
namespace n
{
class foo
{
};
}
typedef n::foo n_foo;
using n::foo;
int main()
{
class foo f1; // ok, declares f1 variable of type n::foo.
class n_foo f2; // error, typedef-name can't be used in elaborated-type-specifier.
}
They have different origins and different uses.
typedef
comes from C
: recall that the C way to declare a struct is:
typedef struct _MyStruct { .... } MyStruct;
It allows you to introduce an alias for a type only. It can be used for the type of a function, with an awkward syntax...
typedef void (*Func)(Foo, Bar);
Where Func
is now a pointer to a function taking two arguments by copy (of types Foo
and Bar
respectively) and returning nothing.
using
has, originally, a different meaning. It is meant to inject a name into a scope. Any name (nearly) can be injected: types, functions, variables (but not enum values...)
With C++11, the syntax has been enhanced to allow template aliasing:
template <typename T>
using equiv_map = std::map<T,T>;
This powered-up using
means that aliasing (see below) is now possible, on top of the previous functionalities.
This C++11 change is a clear direction toward syntax harmonization. Note how the definition of an alias is now similar to the definition of a variable:
<name> = <expression>;
Unfortunately it seems the Standard reserved this aliasing to template situations, so for now both typedef
and using
coexist, each with its own hunting ground.
精彩评论