如何在C++中模拟解构?

Tre*_*key 35 javascript c++ language-construct destructuring c++17

在JavaScript ES6中,有一种称为解构的语言功能.它也存在于许多其他语言中.

在JavaScript ES6中,它看起来像这样:

var animal = {
    species: 'dog',
    weight: 23,
    sound: 'woof'
}

//Destructuring
var {species, sound} = animal

//The dog says woof!
console.log('The ' + species + ' says ' + sound + '!')
Run Code Online (Sandbox Code Playgroud)

我可以在C++中做些什么来获得类似的语法并模拟这种功能?

Esc*_*alo 38

对于std::tuple(或std::pair)对象的特定情况,C++提供了std::tie类似的功能:

std::tuple<int, bool, double> my_obj {1, false, 2.0};
// later on...
int x;
bool y;
double z;
std::tie(x, y, z) = my_obj;
// or, if we don't want all the contents:
std::tie(std::ignore, y, std::ignore) = my_obj;
Run Code Online (Sandbox Code Playgroud)

我完全不像你提出的那样,没有意识到符号的方法.


dal*_*lle 31

在C++ 17中,这称为结构化绑定,它允许以下内容:

struct animal {
    std::string species;
    int weight;
    std::string sound;
};

int main()
{
  auto pluto = animal { "dog", 23, "woof" };

  auto [ species, weight, sound ] = pluto;

  std::cout << "species=" << species << " weight=" << weight << " sound=" << sound << "\n";
}
Run Code Online (Sandbox Code Playgroud)

  • 只是警告这与 JavaScript 版本并不完全等同。如果你在分配列表中交换“weight”和“sound”,那么“[species, sound,weight] = ...”,它会打印“weight=”woof“”和“sound=23”。 (7认同)
  • 我相信这是最新且相关的答案。 (6认同)
  • @MHebes我同意它类似于Javascript中的数组解构(基于索引)而不是Javascript中的对象解构(基于名称)。 (4认同)
  • 当我们不想解构一切时,是否有相当于“std::ignore”的东西? (2认同)

Cha*_*had 6

主要是std::mapstd::tie:

#include <iostream>
#include <tuple>
#include <map>
using namespace std;

// an abstact object consisting of key-value pairs
struct thing
{
    std::map<std::string, std::string> 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;
}
Run Code Online (Sandbox Code Playgroud)