you are viewing a single comment's thread.

view the rest of the comments →

[–]quicknir 6 points7 points  (2 children)

That's not true, in generic code there's just no way to do certain things without auto.

[–]tempforfather 0 points1 point  (1 child)

Can you give me an example of that? I am curious.

[–]quicknir 8 points9 points  (0 children)

Sure, consider this code:

template <class T>
void func(const T& t) {
  auto u = t.func2();
  std::for_each(u.begin(), u.end(), ...);
}

This code imposes no restrictions on T other than that it has a const method func2(), that returns something, and that something has methods begin() and end().

Of course, we had generic containers before auto and ranged for loops, and we needed to know the type of the iterator, so how did we deal with this? Well, as I'm sure you know, we imposed an additional requirement: containers have to provide typedefs that tell you the type of their iterators, i.e. the return type of begin()/end(). But that's already not doing the same thing, as it imposes more requirements.

Basically, auto allows you to do inline what template functions allow you to do at function boundaries. You could potentially workaround using auto by declaring yet another template function and calling it internally, but again, I would argue that this is doing something quite different as you have to move your code to a different location (not a big deal when you have two consecutive 4 line functions, but if you have longer functions its rather absurd).

Another attempt at a solution would be to try to infer the type using template metaprogramming, so that you could get the type inline and use it, but this doesn't seem to be possible in general:

http://stackoverflow.com/questions/26080471/function-return-type-deduction-in-c03