Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 886
Simon Avatar asked Jun 27 '12 10:06

Simon


People also ask

Is using better than typedef?

In C++, 'using' and 'typedef' performs the same task of declaring the type alias. There is no major difference between the two. 'Using' in C++ is considered to define the type synonyms.

What is the difference between using and typedef?

A programmer in modern C++ has two options for declaring new type aliases. The typedef keyword is used to declare new type aliases in the typical way. The using keyword is the new means of declaring new type aliases introduced in C++11.

Should I use typedef in C?

typedef'ing structs is one of the greatest abuses of C, and has no place in well-written code. typedef is useful for de-obfuscating convoluted function pointer types and really serves no other useful purpose.

What is the advantage of using typedef?

Typedefs provide a level of abstraction away from the actual types being used, allowing you, the programmer, to focus more on the concept of just what a variable should mean. This makes it easier to write clean code, but it also makes it far easier to modify your code.


1 Answers

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.

like image 157
daramarak Avatar answered Oct 02 '22 07:10

daramarak