Home > C++11 > C++1y Automatic Type Deduction

C++1y Automatic Type Deduction

The addition, err, redefinition of the auto keyword in C++11 was a great move to reduce code verbosity during the definition of local variables:

auto short name

In addition to this convenient usage, employing auto in conjunction with the new (and initially weird) function-trailing-return-type syntax is useful for defining function templates that manipulate multiple parameterized types (see the third entry in the list of function definitions below).

In the upcoming C++14 standard, auto will also become useful for defining normal, run-of-the-mill, non-template functions. As the fourth entry below illustrates, we’ll be able to use auto in function definitions without having to use the funky function-trailing-return-type syntax (see the useless, but valid, second entry in the list).

auto return type

For a more in depth treatment of C++11’s automatic type deduction capability, check out Herb Sutter’s masterful post on the new AAA (Almost Always Auto) idiom.

  1. Chris
    December 16, 2013 at 2:29 pm

    C++14 adds even more auto support than that:
    auto add = [](auto x, auto y) {return x + y;}

  2. robdesbois
    December 18, 2013 at 6:39 am

    Trailing return type without templates is also useful for out-of-line member function definitions where the return type is a member of the class type:

    struct foo {
    struct blah {};
    blah get_blah();
    };
    //compare:
    foo::blah foo::get_blah() { … }
    auto foo::get_blah() -> blah { … }

    The second one doesn’t need to scope `blah` to `foo`, since the trailing return type is already within that scope. Not a major difference in legibility here, granted, but I find it useful for more verbose types.

    • December 18, 2013 at 7:31 am

      Nice! That’s why I love C++. Just when you think you’ve got a feature down, you learn new, unanticipated uses for it. Thanks.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: