How can I emulate destructuring in C++?

后端 未结 5 1239
轻奢々
轻奢々 2020-12-29 01:44

In JavaScript ES6, there is a language feature known as destructuring. It exists across many other languages as well.

In JavaScript ES6, it looks like this:

5条回答
  •  情话喂你
    2020-12-29 02:08

    Mostly there with std::map and std::tie:

    #include 
    #include 
    #include 
    using namespace std;
    
    // an abstact object consisting of key-value pairs
    struct thing
    {
        std::map kv;
    };
    
    
    int main()
    {
        thing animal;
        animal.kv["species"] = "dog";
        animal.kv["sound"] = "woof";
    
        auto species = std::tie(animal.kv["species"], animal.kv["sound"]);
    
        std::cout << "The " << std::get<0>(species) << " says " << std::get<1>(species) << '\n';
    
        return 0;
    }
    

提交回复
热议问题