What are the differences between typedef and using?

前端 未结 3 817
隐瞒了意图╮
隐瞒了意图╮ 2021-01-01 21:56

What are the differences between using

typedef Some::Nested::Namespace::TypeName TypeName;

or

using Some::Nested::Namespace         


        
相关标签:
3条回答
  • 2021-01-01 22:13

    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.

    0 讨论(0)
  • 2021-01-01 22:31

    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.
    }
    
    
    0 讨论(0)
  • 2021-01-01 22:33

    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.

    0 讨论(0)
提交回复
热议问题