Search code examples
c++c++17autostructured-bindings

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


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?

Solution

  • 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.