在 JavaScript ES6 中,有一个称为 destructuring 的语言功能。 .它也存在于许多其他语言中。
在 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 + '!')
我可以在 C++ 中做什么来获得类似的语法并模拟这种功能?
最佳答案
在 C++17 中,这称为 structured bindings ,它允许以下内容:
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";
}
关于c++ - 如何在 C++ 中模拟解构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31394507/