What are the differences between typedef and using?

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

What are the differences between using

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

or

using Some::Nested::Namespace         


        
3条回答
  •  猫巷女王i
    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 
    using equiv_map = std::map;
    

    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:

     = ;
    

    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.

提交回复
热议问题