Are there features (in particular, structured binding) which I can't use without 'auto'?

Viewed 196

auto keyword was introduced to simplify the code. In particular, iterating over stl containers became way easier and better-looking without having to use the ugly std::vector<MyType>::iterator syntax every time you want to loop over it. However, it was still possible to write code without using auto which would do exactly the same thing.

Now (I think) you can't use certain features without auto, in particular structured bindings:

std::tuple<int, int&> f();
auto [x, y] = f();

So, two questions:

  1. Am I correct that there's no way to initialize [x, y] without using auto (still using structured bindings)? Is there a way to initialize it explicitly: *explicit_type* [x, y] = f();?
  2. What other features require using auto?
2 Answers

Am I correct that there's no way to initialize [x, y] without using auto (still using structured bindings)?

Yes, this is correct. The grammar specifies no other way, as can be seen for example here.

What other features require using auto?

A classical example should be the (generic) lambda expressions:

auto lambda = [](auto&&...) { };

But as stated in the comments, there are some other examples as well.

cppreference is quite clear concerning point 1/, see Structured binding declaration, C++17

attr(optional) cv-auto ref-operator(optional) [ identifier-list ]

where cv-auto is possibly cv-qualified type specifier auto

For 2/ I have two examples:

  1. the already cited auto = [](){}; lambda case

  2. the other one is C++17 Declaring non-type template arguments with auto

An usage example is:

template <typename Type, Type value> constexpr Type TConstant = value;

that can be simplified, in C++17, by:

template <auto value> constexpr auto TConstant = value;
Related