How can I declare and define multiple variables in one line using C++?

后端 未结 10 1736
抹茶落季
抹茶落季 2020-11-27 11:09

I always though that if I declare these three variables that they will all have the value 0

int column, row, index = 0;

Bu

10条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 11:51

    As others have mentioned, from C++17 onwards you can make use of structured bindings for multiple variable assignments.

    Combining this with std::array and template argument deduction we can write a function that assigns a value to an arbitrary number of variables without repeating the type or value.

    #include 
    #include 
    
    template  auto assign(T value)
    {
        std::array out;
        out.fill(value);
        return out;
    }
    
    int main()
    {
        auto [a, b, c] = assign<3>(1);
    
        for (const auto& v : {a, b, c})
        {
            std::cout << v << std::endl;
        }
    
        return 0;
    }
    

    Demo

提交回复
热议问题