C++ 'typedef' vs. 'using … = …' [duplicate]

一曲冷凌霜 提交于 2019-12-21 03:12:16

问题


Possible Duplicate:
What are the differences between typedef and using in C++11?

The following code compiles and runs. My question is what is the difference between the "typedef" and "using" method for renaming the template specialization?

template<typename T>
struct myTempl{
    T val;
};

int main (int, char const *[])
{
    using templ_i = myTempl<int>;
    templ_i i;
    i.val=4;

    typedef myTempl<float> templ_f;
    templ_f f;
    f.val=5.3;

    return 0;
}

Edit:

If there is no difference, which one would you prefer? / Why was the using ... = ... version introduced?


回答1:


They are the same.

To quote the C++11 standard (or the draft to be specific):

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

I think the "the same semantics as the typedef specifier" say it all.



来源:https://stackoverflow.com/questions/11224336/c-typedef-vs-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!