SwiftMango
SwiftMango

Reputation: 15284

What is the use of auto?

I understand we can use auto like:

auto a = 1;
auto b = Foo(1,2);

Or in the function call:

auto foo(){
  return Foo(1,2);
}

But C++11 also provides uniform initialization and initialization list, so we can do:

Foo a {1,2};
Foo b = {1,2};
Foo foo(){
  return {1,2};
}

So what is the use of auto if we already have braces syntax? (except define a primitive type)

Upvotes: 0

Views: 156

Answers (3)

Shoe
Shoe

Reputation: 76240

I think the best use of auto can be seen when you use it with the good ol' iterators. Compare:

for (std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it)

to:

for (auto it = vector.begin(); it != vector.end(); ++it)

Even though, in C++11 we have range-fors that helps out a lot better, iterators are still widely used in cases where your range is not well defined or you need to perform action on the elements.

In general, auto can be useful when a type, that is a PITA to type, can be automatically inferred by the compiler.

Upvotes: 6

kliteyn
kliteyn

Reputation: 1987

auto is best for templates and iterators.

Not only it can really simplify the syntax and improve code readability, but it can also obsolete some extensive template usage.

Check out this guy's page - very nice and to the point.

Conciser the following:

template <typename BuiltType, typename Builder>
void makeAndProcessObject (const Builder& builder) {
    BuiltType val = builder.makeObject();
    // ...
}

Now with auto you can get rid of the multiple types in the template:

template <typename Builder>
void makeAndProcessObject (const Builder& builder)
{
    auto val = builder.makeObject();
    // ...
}

Moreover, when you actually call this function, you don't need to provide any type as a template parameter:

MyObjBuilder builder;
makeAndProcessObject(builder);

Upvotes: 1

user1508519
user1508519

Reputation:

When the return type is unspecified you need auto. For example, std::bind.

using namespace std::placeholders;
int n = 7;
auto f1 = std::bind(f, _2, _1, 42, std::cref(n), n);

Upvotes: 2

Related Questions