Comment

Comment by susam

> If I come across a structured binding where x and y are auto assigned as the unpacking of struct fields whose types might be complicated, now I have local variables x and y that I cannot reason about ...

One is free to not use the auto keyword in a scenario like you mention in order to make the types explicit regardless of what the "Almost Always Auto" camp says.

However there are scenarios where leaving the type out does not degrade readability and sometimes improves readability. Often cited examples of situations where it may improve readability usually look somewhat like this:

    void print_vector_of_maps(std::vector<std::map<std::string, std::string>> v)
    {
        for (const std::map<std::string, std::string>& item: v) {
            for (const std::pair<std::string, std::string>& entry: item) {
                std::cout << entry.first << ": " << entry.second << '\n';
            }
            std::cout << "---\n";
        }
    }
With the auto keyword, it looks like this:

    void print_vector_of_maps(std::vector<std::map<std::string, std::string>> v)
    {
        for (const auto& item: v) {
            for (const auto& entry: item) {
                std::cout << entry.first << ": " << entry.second << '\n';
            }
            std::cout << "---\n";
        }
    }
The types are still known from the surrounding context and the readability has arguably improved.
parent susam 8 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton