What is the difference between 'typedef' and 'using' in C++11?

后端 未结 7 819
误落风尘
误落风尘 2020-11-22 03:32

I know that in C++11 we can now use using to write type alias, like typedefs:

typedef int MyInt;

Is, from what I

7条回答
  •  情话喂你
    2020-11-22 03:56

    I know the original poster has a great answer, but for anyone stumbling on this thread like I have there's an important note from the proposal that I think adds something of value to the discussion here, particularly to concerns in the comments about if the typedef keyword is going to be marked as deprecated in the future, or removed for being redundant/old:

    It has been suggested to (re)use the keyword typedef ... to introduce template aliases:

    template
      typedef std::vector > Vec;
    

    That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages [sic] among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector<•, MyAllocator<•> > – where the bullet is a placeholder for a type-name.Consequently we do not propose the “typedef” syntax.On the other hand the sentence

    template
      using Vec = std::vector >;
    

    can be read/interpreted as: from now on, I’ll be using Vec as a synonym for std::vector >. With that reading, the new syntax for aliasing seems reasonably logical.

    To me, this implies continued support for the typedef keyword in C++ because it can still make code more readable and understandable.

    Updating the using keyword was specifically for templates, and (as was pointed out in the accepted answer) when you are working with non-templates using and typedef are mechanically identical, so the choice is totally up to the programmer on the grounds of readability and communication of intent.

提交回复
热议问题