31

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?

Community
  • 1
  • 1
Simon
  • 961
  • 2
  • 9
  • 14
  • A `using` that is not a template is not really the use-case this was introduced for. – pmr Jun 27 '12 at 10:42
  • 1
    -1. exact dublicate: http://stackoverflow.com/questions/10747810/what-is-the-difference-between-typedef-and-using-in-c11 – Andrew Jun 27 '12 at 10:43
  • 1
    @Andrew You're right, I just wan't able to find that. – Simon Jun 27 '12 at 10:57
  • @Simon: first link in google: https://www.google.com/#hl=en&sclient=psy-ab&q=c%2B%2B+11+typedef+vs+using&oq=c%2B%2B+11+typedef+vs+using&gs_l=hp.3...1866.13293.0.13428.35.27.6.2.2.0.299.3079.13j10j3.26.0...0.0.Bzu6yzNHsAU&pbx=1&bav=on.2,or.r_gc.r_pw.r_qf.,cf.osb&fp=7e21084bce2178cc&biw=1276&bih=706 – Andrew Jun 27 '12 at 10:59
  • 3
    Have you noticed that C++11 is moving to a left-to-right declaration style everywhere? The use of `using` to write type alias is more consistent with new C++11 style. The phrase is from Herb Sutter http://herbsutter.com/2013/08/12/gotw-94-solution-aaa-style-almost-always-auto/ – Zhen Aug 20 '13 at 14:45

1 Answers1

38

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.

Flexo
  • 87,323
  • 22
  • 191
  • 272
daramarak
  • 6,115
  • 1
  • 31
  • 50